I'm not quite understanding 开发者_运维百科lambda functions. Here is an example function from the book Land of Lisp:
(defun edges->dot (edges)
(mapc (lambda (node)
(mapc (lambda (edge)
(fresh-line)
(princ (dot-name (car node)))
(princ "->")
(princ (dot-name (car edge)))
(princ "[label=\"")
(princ (dot-label (cdr edge)))
(princ "\"];"))
(cdr node)))
edges))
Let's just look at the inner part here for now:
(mapc (lambda (edge)
(fresh-line)
(princ (dot-name (car node)))
(princ "->")
(princ (dot-name (car edge)))
(princ "[label=\"")
(princ (dot-label (cdr edge)))
(princ "\"];"))
(cdr node)))
I understand that the function mapc
takes two arguments, a function and a list. I also understand that by using lambda (node)
I am passing an anonymous function that takes one argument (node
) as the first argument to mapc
, and that (cdr node)
will be used as the second argument to mapc
. At least I think that's what's going on!
What I don't understand is where my anonymous function gets the value for edge
in (lambda (edge)
. I would appreciate it if someone could please explain this to me.
The edge
argument comes from the items in (cdr node)
. Your inner lambda will be called once for each element in (cdr node)
.
Try this for example:
(mapc #'princ '(1 2 3 4 5))
Or, with a literal lambda:
(mapc #'(lambda (x)
(princ x)
(terpri))
'(1 2 3 4 5))
精彩评论