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
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:
References:
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
- 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
(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:
- Basic generators
- Basic comprehensions
- Multiple generators (nested loops) and qualifiers (filtering)
- Advanced Generators
- Multiple accumulators
- Defining custom comprehensions
References:
- SRFI 42 by Sebastian Egner
- "Eager Comprehensions in Scheme: The design of SRFI-42" by Sebastian Egner
Labels: eager comprehension
0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home