CS 3723/3721
Programming Languages
Use of mapcar and apply


mapcar and apply:

    Lisp has special types of functions that transform and expand the meaning of other functions. The most common of these is mapcar. Consider where f is a function and list1, list2, ..., listn are lists. The result of this is to make up a new list that looks like: Thus Similarly, (apply 'f '(s1 s2 ... sn)) becomes (f 's1 's2 ... 'sn) so that one has:

Example: the transpose function:

    Check out the following transpose function for matrices. This code shows some of the real power of Lisp and of functional programming. A transpose function in a traditional language is much more complicated.

    First define some matrices in Lisp:

    Here is how one might define a transpose in a traditional way:

    However, the two "helper" functions can be defined in a simpler way using mapcar:

    Substituting these into the definition for transpose produces the following elegant version:


Functional Programming:


Revision date: 2004-03-19. (Please use ISO 8601, the International Standard Date and Time Notation.)