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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With