What is the difference between "apply" and "mapcar" in Lisp

(defun describe-paths (location edges) (apply #'append (mapcar #'describe-path (cdr (assoc location edges))))) 
+7
source share
2 answers

What are the similarities? Or is there another question lurking here?

(Links from elisp because this is what I know. Quotation marks are just excerpts, and links contain examples that 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 should be a sequence.

apply (in call functions)

applying a call function with arguments is simple , like funcall, but with one difference: the last of the arguments is a list of objects that are passed as separate arguments , not just a single list. We say that applying this list is distributed in such a way that each individual element becomes an argument.

Happy coding.

+11
source

The describe-paths function (from a text adventure game in Lisp Earth !) Generates descriptions for paths from a specific location. Pages 74-77 in Lisp Earth explain the roles of mapcar and append in this example.

(cdr (assoc location edges)) contains a list of all the paths going from the location, for example, for the living-room location:

 ((GARDEN WEST DOOR) (ATTIC UPSTAIRS LADDER)) 

mapcar calls the describe-path function for each of the paths, collecting the path descriptions in a list in which each of the subscriptions 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, combining it into a flat list:

 (THERE IS A DOOR GOING WEST FROM HERE. THERE IS A LADDER GOING UPSTAIRS FROM HERE.) 
+4
source

All Articles