The less-familiar parts of Lisp for beginners — reduce

Our next stop on the brief alphabetical tour through less commonly-used Lisp features is reduce.  This function is used to apply a binary function over a sequence.  The output of the function must be compatible with its input, as it feeds back into itself.

If the keyword argument from-end is nil (the default), then the function is applied first to the first two elements of the sequence.  The result of this function becomes the first input to the next invocation of the function, the second argument of which is the third element in the sequence.  The output again feeds into the function, with the second argument being taken from the fourth element in the sequence, until the sequence is exhausted.  If from-end is non-nil, the first call to the function takes arguments of the second-from-last and last elements of the sequence in that order.  Following invocations take the results of the previous function calls as the second parameter, and walk backwards through the sequence to obtain the first argument.

It is also possible to prime the function with an initial value, which becomes the first parameter to the first function call in the case where from-end is nil, and the second parameter to the first function call in the case where from-end is non-nil.

The edge cases are these:  If the sequence has no elements, and no initial value is supplied, the function is called with no arguments, and has to be able to handle that case.  If the sequence has exactly one element and no initial value is supplied, the function is not called, the single element’s value is returned.  If the sequence has no elements, but has an initial value, the function is not called, and the initial value is returned.  All other cases proceed according to the general case described above.  Also note that there are keyword arguments to select a subsequence, by choosing the start and/or end of the range within the sequence.

One way one might use this function is in applying a sequence of linear transformations with square matrix multiplications.  The matrices are queued up in a list, and then reduce is used to perform the multiplication to produce the net transformation matrix.  You can also use reduce on simple arithmetic operations like + and *, but note that it may be more efficient in those specific cases to use apply, as those operations take an arbitrary number of arguments already.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.