for vs map

35 views
Skip to first unread message

letronje

unread,
Mar 6, 2013, 1:03:12 AM3/6/13
to clj-...@googlegroups.com
Context: http://www.4clojure.com/problem/99

One way to solve this is:

(fn [a b]
  (map #(- (int %) 48)
       (str (* a b))))

A slight variant would be to use a for comprehension,

(fn [a b]
  (for [d (str (* a b))]
    (- (int d) 48)))

From the above two, Which is preferable/recommended and why ?

The general question is whether to use 'for' or 'map' while generating new values from values in a single collection.

Baishampayan Ghose

unread,
Mar 6, 2013, 1:21:48 AM3/6/13
to clj-...@googlegroups.com
Manoj,

`map` is a higher order function that maps a function over a sequence.
The length of the result sequence will always be the same as that of
the original sequence.

`for` on the other hand is a list-comprehension function and as such
allows you to "generate" elements given certain conditions.

In your case, there is really no difference between the two and I'd
prefer a `map` here as you don't really need `for`, but in certain
cases you must use `for` as `map` won't just cut it.

For example, what if I want to take in a sequence of numbers and emit
only the odd numbers from the sequence after adding one?

You can't use `map`, but `for` will do the trick -

(for [x xs :when (odd? x)]
(inc x))

;; a combination of `filter` & `map` will work as well

And this is how I solved #99 -

(fn [x y]
(map #(Integer/parseInt (str %)) (str (* x y))))

Regards,
BG
> --
> You received this message because you are subscribed to the Google Groups
> "Clojure Users Group Pune" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to clj-pune+u...@googlegroups.com.
> Visit this group at http://groups.google.com/group/clj-pune?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>



--
Baishampayan Ghose
b.ghose at gmail.com
Reply all
Reply to author
Forward
0 new messages