6.6

2 Examples

Obviously, the primary purpose of generic collections is the ability to operate on values in a collection-agnostic way. For example, it is possible to map over all kinds of sequences, even sequences of heterogenous types.

> (sequence->list (map + #(1 2 3) (stream 10 20 30)))

'(11 22 33)

However, more interesting applications of generic collections involve the ability to use lazy sequences to create infinite streams of values. For example, it is possible to create an infinite stream of all the Fibonacci numbers:

> (define fibs (stream-cons 1 (stream-cons 1 (map + fibs (rest fibs)))))
> (sequence->list (take 15 fibs))

'(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610)

Similarly, here is an implementation of the classic “fizz buzz” problem that uses infinite sequences:

> (define ((divisible-by? x) n)
    (zero? (remainder n x)))
> (define fizzbuzz
    (map
     (match-lambda
       [(? (divisible-by? 15)) 'fizzbuzz]
       [(? (divisible-by?  3)) 'fizz]
       [(? (divisible-by?  5)) 'buzz]
       [n                      n])
     (in-naturals 1)))
> (sequence->list (take 20 fizzbuzz))

'(1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz)