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.

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, so would it be correct to say that the first argument of mapc must be a function of only one argument?
@MikeJerome: Correct, if you're passing in one list. In general, your function takes as many arguments as lists you're passing in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.