This "back-quoting" technique is a great feature in Lisp- it
lets us write code that looks just like the data it
creates. This happens frequently with code written in a
functional style: By building functions that look like
the data they create, we can make our code easier to understand
and also build for longevity: As long as the data doesn't
change, the functions will probably not need to be refactored
or otherwise changed, since they mirror the data so closely.
Imagine how you'd write a function like this in VisualBasic or
C: You would probably chop the path into pieces, then append
the text snippets and the pieces together again - a more
haphazard process that "looks" totally different from the data
that is created and probably less likely to have longevity.
|
Now we can describe a path, but a location in our game may
have more than one path, so let's create a function called
describe-paths:
|
(defun describe-paths (location map)
(apply #'append (mapcar #'describe-path (cddr (assoc location map)))))
|
This function uses another common Functional Programming
technique: The use of Higher Order Functions - This
means that the apply and mapcar functions
are taking other functions as parameters so that they can call
them themselves. To pass a function, you need to put
#' in front of the function name. The cddr
command chops the first two items from the front of the list
(so only the path data remains). The mapcar simply
applies another function to every object in the list, basically
causing all paths to be changed into pretty descriptions by the
describe-path function. The apply #'append
just cleans out some parentheses and isn't so important. Let's
try this new function:
|
(describe-paths 'living-room map)
|
==> (there is a door going west from here - there is a stairway
going upstairs from here -)
|
Beautiful!
|
<< begin
< previous -
next >
end >>
|