A set of high-level mapping functions is available in Common Lisp, to apply a function to the elements of one or more lists. They differ in the way in which the function is applied to the lists and how the final result is obtained. The following table summarize the differences and shows for each of them the equivalent LOOP form. f is the function to be applied, that must have a number of arguments equal to the number of lists; “applied to car” means that it is applied in turn to the elements of the lists, “applied to cdr” means that it is applied in turn to the lists, their cdr, their cddr, etc.; the “returns” column shows if the global result is the obtained by listing the results, concatenating them (so they must be lists!), or simply used for side-effects (and in this case the first list is returned).
Function | Applied to | Returns | Equivalent LOOP |
---|---|---|---|
(mapcar f l1… ln) | car | list of results | (loop for x1 in l1… for xn in ln collect (f x1… xn)) |
(maplist f l1… ln) | cdr | list of results | (loop for x1 on l1… for xn on ln collect (f x1… xn)) |
(mapcan f l1… ln) | car | concatenation of results | (loop for x1 in l1… for xn in ln nconc (f x1… xn)) |
(mapcon f l1… ln) | cdr | concatenation of results | (loop for x1 on l1… for xn on ln nconc (f x1… xn)) |
(mapc f l1… ln) | car | l1 | (loop for x1 in l1… for xn in ln do (f x1… xn) finally (return l1)) |
(mapl f l1… ln) | cdr | l1 | (loop for x1 on l1… for xn on ln do (f x1… xn) finally (return l1)) |
Note that, in all the cases, the lists can be of different lengths, and the application terminates when the shortest list is terminated.
Another couple of map functions are available: map
, that can be applied to sequences (strings, vectors, lists), analogous to mapcar
, and that can return any type of sequence, specified as first argument, and map-into
, analogous to map
, but that destructively modifies its first sequence argument to keep the results of the application of the function.