What is the difference between "apply" and "mapcar" in Lisp
What are the similarities? Or, is there another question lurking here?
(Links from elisp, because that is what I know. The quotes are just excerpts and the links contain examples which may or may not be relevant in a particular "Lisp".)
mapcar
mapcar is a function that calls its first argument with each element of its second argument, in turn. The second argument must be a sequence.
apply (in Calling Functions)
apply calls function with arguments, just like funcall but with one difference: the last of arguments is a list of objects, which are passed to function as separate arguments, rather than a single list. We say that apply spreads this list so that each individual element becomes an argument.
Happy coding.
The describe-paths
function (from the text based adventure game in Land of Lisp!) generates descriptions for the paths going from a given location. Page 74-77 in Land of Lisp explains the roles of mapcar
and append
in the example.
The (cdr (assoc location edges))
provides a list of all paths going from the location, such as these for the living-room
location:
((GARDEN WEST DOOR)
(ATTIC UPSTAIRS LADDER))
The mapcar
calls the function describe-path
for each of the paths, collecting the path descriptions into a list where each of the sublists is a path description:
((THERE IS A DOOR GOING WEST FROM HERE.)
(THERE IS A LADDER GOING UPSTAIRS FROM HERE.))
Next the append
function is applied to the list of path descriptions, concatenating it into a flat list:
(THERE IS A DOOR GOING WEST FROM HERE. THERE IS A
LADDER GOING UPSTAIRS FROM HERE.)