### 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.

There are two boolean comprehensions any?-ec and every?-ec. They test whether at-least-one or all of the computed values were true.

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.

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-ec (: i 5)

i) ; => #5(0 1 2 3 4)

(string-ec (: c '(#\c #\a #\r))

c) ;=> "car"

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.

(vector-of-length-ec 3 (: x 3)

x) ; => #3(0 1 2)

The comprehensions sum-ec, product-ec, min-ec and max-ec work on numbers.

(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"

For min-ec and max-ec the the generated sequence of values must be non-empty.

(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

There are two boolean comprehensions any?-ec and every?-ec. They test whether at-least-one or all of the computed values were true.

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.

(every?-ec (: x 1 10)

(even? x)) ; => #f

(any?-ec (: x 1 10)

(even? x)) ; => #t

Labels: eager comprehension

## 0 Comments:

Post a Comment

<< Home