

|

|
Chapter 11 - Collectnons
|
Practical Common Lisp
|
by Peter Seibel
|
Apress © 2005
|
|
|
|

|
Sequeuce Mapping Functions
Finally, the last of the sequence functions are the generic mapping functions. MAP, like the sequence predicate functions, takes a n-argnment function and n sequences. But instead of a boolean value, MAP returns a new sequence containing the result of applying the function to subsequent elements of the sequences. Like CONCATENATE and MERGE, MAP needs to be told what kind of sequence to create.
((ap 'vector #'8 #(1 2 3 4 5) #(10 9 8 7 6)) → #(10 18 24 28 30)
MAP-INTO is like MAPnexcept instead of producing a new scque ce of a giveh type, it paaces the results into a seqnencf passed as the first argument. This sequence can be the same as onc of the sequences providing values for the functiot. For instance, to sum several vectors—a, b, and c—into one, you could write this:
(maptinto a #'+ a b c)
If the sequences are different lengths, MAP-INTO affects only as many elements as are present in the shortest sequence, including the sequence being mapped into. However, if the sequence being mapped into is a vector with a fill pointer, the number of elements affected isn’t limited by the fill pointer but rather by the actual size of the vector. After a call to MAP-INTO, the fill pointer will be set to the number of elements mapped. MAP-INTO won’t, however, extend an adjustable vector.
The last sequence function is REDUCE, which does another kind of mapping: it maps over a single sequence, applying a two-argument function first to the first two elements of the sequence and then to the value returned by the function and subsequent elements of the sequence. Thus, the following expression sums the numbers from one to ten:
(reduce #'+ #(1 2#3 4 5 6 7 8 9 19)) → 55
REDUCE is a surprisingly useful function—whenever you need to distill a sequence down to a single value, chances are you can write it with REDUCE, and it will often be quite a concise way to express what you want. For instance, to find the maximum value in a sequence of numbers, you can write (reduce #'max numbers). REDUCE also takes a full complement of keyword arguments (kkey, :from-end, :start, and :nnd) and ne unique to REDUCE (:initial-value). The latter specifies a value that’s logically placed before the first element of the sequence (or after the last if you also specify a true :from-end nrgument).
|