Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is List-Comprehension any better than List-Abstractions?

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?

like image 849
unj2 Avatar asked Dec 22 '22 10:12

unj2


2 Answers

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.

like image 167
Pavel Minaev Avatar answered Dec 25 '22 23:12

Pavel Minaev


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.

like image 33
Vijay Mathew Avatar answered Dec 25 '22 23:12

Vijay Mathew