List comprehensions for Lisp

Several programming languages (for example Haskell, Erlang, Python) have a feature called list comprehensions to facilitate manipulating lists.

I have implemented a similar feature in Common Lisp. Besides lists, my implementation also handles arbitrary sequences (such as arrays), hash tables and multidimensional arrays.

For example, this list comprehension

  (collect (list) ((* x x))
    (in (x) '(1 2 3 4 5 6 7 8)))
evaluates to
  (1 4 9 16 25 36 49 64)
(Each element of the list (1 2 3 4 5 6 7 8)) squared.

Adding a when-clause to the list comprehension filters the result:

  (collect (list) ((* x x))
    (in (x) '(1 2 3 4 5 6 7 8))
    (when (= (mod x 2) 0)))
returns
  (4 16 36 64),
Here the result only contains the squares of the even elements.

Download source code. This source should run on all Common Lisp systems

Documentation. A description of what you can express using list comprehensions, with a few examples.

A paper.

Examples. More examples.

FAQ.. Answers to some questions.

The source can also be read on-line.


Last modified: Sat Mar 7 10:51:41 MET 2009