1

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.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
MikeJerome
  • 660
  • 6
  • 20

1 Answers1

2

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))
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • Okay, so would it be correct to say that the first argument of mapc must be a function of only one argument? – MikeJerome Sep 16 '11 at 00:18
  • @MikeJerome: Correct, if you're passing in one list. In general, your function takes as many arguments as lists you're passing in. – C. K. Young Sep 16 '11 at 02:04