Tuesday, August 08, 2006

Eager Comprehensions for Black Belts - An SRFI 42 Tutorial

Eager comprehensions from SRFI-42 provide a convenient notation for writing loops generating a sequence of values, and optionally accumulating the values into a result. Inspired by Peter Seibel's chapter "LOOP for Black Belts" in "Practical Common Lisp" the following is an attempt to show the utility of eager comprehensions.

Eager comprehensions (think: loops) can sequentially bind variables to numbers in a numerical range
  • sequentially bind variables to elements in a data structure
  • execute arbitrary Scheme expressions
  • conditionally perform parts of the loop
An eager comprehension consists normally of 3 components:
  • a comprehension, that accumulates the result
  • some generators, that produces sequences of values
  • an expression that uses the generated values, to
    compute a value, the comprehension can accumulate
This sounds worse than it is, so consider the example:

(require (lib "42.ss" "srfi"))
(list-ec (: i 5)
(* i 2))
; => (0 2 4 6 8)

The generator (: i 5) binds in turn i to 0, 1, 2, 3, and 4.
The expression (* i 2) is evaluated for each binding of i.
The computed values 0, 2, 4, 6 and 8 are accumulated by the comprehension list-ec. The list comprehension list-ec accumulates the computed values into a list.

The master plan is now as follows:
  1. Basic generators
  2. Basic comprehensions
  3. Multiple generators (nested loops) and qualifiers (filtering)
  4. Advanced Generators
  5. Multiple accumulators
  6. Defining custom comprehensions
Expect one post a day.

References:

Labels:

0 Comments:

Post a Comment

<< Home