views:

170

answers:

3

Why do people prefer list comprehensions like
(for [x '(1 2 3)] (* 2 x)) instead of (map #(* %1 2) '(1 2 3))?

Are there benefits to this kind of programming?
1. Is it more readable?
2. Is it faster in some cases? 3. Is it better for certain kinds of operations and data structures?

+4  A: 

For your given example, there are no benefits; but in general, for is useful when you're joining two (or more) sequences, or when you need to do some filtering - a for with :let and :when is usually more readable than a chain of nested map and filter.

Pavel Minaev
A: 

list comprehensions are used for cases where you need to iterate through sequences in more complex ways. in your example they are the same so I would recoment map because its easier to read.

map cant gets ugly for do this for example:

(for [x '(1 2 3) y '(3 2 1)] (* 2 x y))
Arthur Ulfeldt
A single `map` cannot, but `mapcat` can. In general, it is always possible to replace a list comprehension with some combination of `map`, `mapcat`, `filter`, and `take-while`. It's just the result can be very hard to read for more complicated cases.
Pavel Minaev
true that! edited to match reality :)
Arthur Ulfeldt
no though it does not do the same thing as the for above. I believe you could drop the (list and just use map to get the same effect as this. the code in the exmaple iterates through all combinations of x and y. like 2 nested for loops in java.
Arthur Ulfeldt
You are correct. We need two maps to do those nested loop things. So is it just about making your codes more readable? What do the list comprehensions expand to?
kunjaan
+2  A: 

List comprehensions are merely "syntactic sugar" over standard functional programs but they give an intuitive reading of common operations over lists. -- Guy Lapalme

Their only intent is better readability. Don't expect any significant performance improvement by using them.

This paper give some insights into implementing List comprehensions in Lisp like languages.

Vijay Mathew