Wednesday, August 09, 2006

Eager Comprehensions for Black Belts - 2. Basic Comprehensions

2. Basic Comprehensions

Comprehensions accumulate the values generated into a result. So far the only comprehension used have been list-ec. There are multiple comprehensions to choose from, when deciding how to accumulate the computed values.

The comprehensions vector-ec and string-ec are analogous to list-ec. The accumulated values of string-ec must all be characters.

(vector-ec (: i 5)
i) ; => #5(0 1 2 3 4)

(string-ec (: c '(#\c #\a #\r))
c) ;=> "car"
If the length of the result vector is known ahead of time, one can use vector-of-length-ec, which is more efficient than vector-ec.

(vector-of-length-ec 3 (: x 3)
x) ; => #3(0 1 2)
Instead of first generating a list of lists, or a list of strings and then applying append or string-append, it is more convenient to use append-ec and string-append-ec.

(append-ec (: x '((1 2) (3 4 5) (6)))
x) ; => (1 2 3 4 5 6)

(string-append-ec (: x '("foo" "bar" "qux"))
x) ; => "foobarqux"
The comprehensions sum-ec, product-ec, min-ec and max-ec work on numbers.
    
(sum-ec (: x '(1 2 3 4))
x) ;=> 10

(product-ec (: x '(1 2 3 4))
x) ; => 24

(min-ec (: x '(1 2 3 4))
x) ; => 1

(max-ec (: x '(1 2 3 4))
x) ; => 4
For min-ec and max-ec the the generated sequence of values must be non-empty.

There are two boolean comprehensions any?-ec and every?-ec. They test whether at-least-one or all of the computed values were true.
   
(every?-ec (: x 1 10)
(even? x)) ; => #f

(any?-ec (: x 1 10)
(even? x)) ; => #t
Note: any?-ec and every?-ec (just as their cousins or and and) are "early stopping". As soon as any?-ec encounters a #t it stops. every?-ec stops when a #f is seen.

Labels:

0 Comments:

Post a Comment

<< Home