On Mon, Dec 22, 2008 at 10:23 AM, Piotr 'Qertoip' Włodarek
<qert...@gmail.com> wrote:
>
> Being new to Clojure, to Lisp and to functional programming in
> general, I have some trouble wraping my head around it.
>
> As the first exercice, I would like to print multiplication table of
> specified order, like:
> (print-multiplication-table 3)
>  1  2  3
>  2  4  6
>  3  6  9
>
> I came that far:
>
> (defn multiplication-row [n k]
>    (map (partial * k) (range 1 (inc n))))
>
> (defn multiplication-table [n]
>    (map (partial multiplication-row n) (range 1 (inc n))))
>
> (println (multiplication-table 3))    ; => ((1 2 3) (2 4 6) (3 6 9))
>
> Now, how to pretty print this?
>
> This does not work - prints nothing - why?:
> (defn pretty-print-row [row]
>  (map print row))

The problem is that you are using map in two different ways here. In
the multiplication-row and multiplication-table functions you are
using it correctly as a function that applies a given function to all
of the values in a collection, returning the results in a new
collection. In the pretty-printing function you do not care about the
results like you did in the above two functions, you care about the
side-effects. For this, you can use doseq:

1:1 user=> (defn multiplication-row [n k]
  (map (partial * k) (range 1 (inc n))))
#'user/multiplication-row
1:3 user=> (defn multiplication-table [n]
  (map (partial multiplication-row n) (range 1 (inc n))))
#'user/multiplication-table
1:5 user=> (defn pretty-print-row [row]
  (doseq [v row] (print v \space)) (print \newline))
#'user/pretty-print-row
1:7 user=> (defn print-multiplication-table [n]
  (doseq [row (multiplication-table n)] (pretty-print-row row)))
#'user/print-multiplication-table
1:9 user=> (print-multiplication-table 3)
1  2  3
2  4  6
3  6  9
nil
1:10 user=> (print-multiplication-table 5)
1  2  3  4  5
2  4  6  8  10
3  6  9  12  15
4  8  12  16  20
5  10  15  20  25
nil

HTH,

- J.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to