| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
srfi-42 - Eager comprehensions This module provides a generic comprehension mechanism, which some other languages (e.g. Haskell and Python) provides as a built-in mechanism. It provides rich set of operators so it can be used as not only a list generator but a generic loop construct (actually, some may say it is as powerful/evil as Common Lisp's loop macro).
It is also runs eagerly, that is, if it generates a list, it creates the entire list when evaluated, instead of generate the elements on demand. Thus it can't represent an infinite sequence, which Haskell's comprehension naturally can. In Scheme, you can use streams built on top of delayed evaluation for such purpose.
Let's begin with some examples.
Generate a list of squares for the first five integers:
(list-ec (: i 5) (* i i)) ⇒ (0 1 4 9 16) |
Generate set of pair of numbers (x y), where x
is between 2 (inclusive) and 5 (exclusive),
and y is between 1 (inclusive) and x (exclusive).
(list-ec (: x 2 5) (: y 1 x) (list x y)) ⇒ ((2 1) (3 1) (3 2) (4 1) (4 2) (4 3)) |
The above two examples can be written in Haskell as the followings:
[ i*i | i <- [0..4] ] [ (x,y) | x <- [2..4], y <- [1..x-1] ] |
Note the differences: (1) In Haskell, the body expression to yield the elements comes first, followed by qualifiers (selectors). In srfi-42, the body expression comes last. (2) In srfi-42, range operator's lower bound is inclusive but its upper bound is exclusive.
List a set of numbers (a b c d), where a^3+b^3 = c^3+d^3:
(define (taxi-number n)
(list-ec (: a 1 n)
(: b (+ a 1) n)
(: c (+ a 1) b)
(: d (+ c 1) b)
(if (= (+ (expt a 3) (expt b 3))
(+ (expt c 3) (expt d 3))))
(list a b c d)))
|
You can generate not only a list, but other sequences:
(vector-ec (: i 5) i) ⇒ #(0 1 2 3 4) (string-ec (: i 5) (integer->char (+ i 65))) ⇒ "ABCDE" |
Or apply folding operations:
(sum-ec (: i 1 100) i) ⇒ 4950 ;; sum of integers from 1 below 100. (product-ec (: i 1 10) i) ⇒ 362880 ;; ... and product of them. |
Each comprehension takes the following form.
(comprehension-macro qualifier … body) |
Evaluates body repeatedly as specified by qualifiers. Depending on the type of comprehension, the results of body may be either collected to create an aggregate (list, vector, string, ...), folded by some operator (sum, product, min, max, ...), or simply discarded.
A few comprehensions takes extra values before qualifiers or after bodies.
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
[SRFI-42]
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] |
This document was generated by Shiro Kawai on October, 7 2008 using texi2html 1.78.