12

Take this function:

(defun sum-greater (x y z)
 (> (+ x y) z))

It's my understanding that in LISP the first element in a list always represents a function to be performed on the subsequent atoms/lists. So why doesn't LISP treat the x in (x y z) as a function to be performed on y and z. Clearly this would not be desirable behavior, but it would be the expected behavior.

Presumably the function that defines defun somehow overrides the standard LISP evaluation of a list? If so, could you detail this?

Thanks

Peter Le Bek
  • 982
  • 8
  • 16
  • 3
    It delays evaluation on all of its other arguments, too: you obviously don't want `(> ...)` evaluated when you evaluate the `defun` form, either! – Ken Nov 16 '10 at 16:05
  • Good point, I should have recognised defun was more than a regular function from that alone.. – Peter Le Bek Nov 16 '10 at 16:06

5 Answers5

8

IIRC in Common Lisp at least defun is a macro (HyperSpec), meaning it may define any evaluation strategy whatsoever for its arguments.

Derrick Turk
  • 4,246
  • 1
  • 27
  • 27
  • 1
    Ah right, that makes sense. I haven't reached the macro chapter of my LISP book yet. FYI - chose this answer because it's most concise, but thanks everyone. – Peter Le Bek Nov 16 '10 at 16:03
6

defun is special because it is a macro. And since macros can be implementation dependent, all sorts of black magic can happen beneath the hood.

Lisp HyperSpec (Common Lisp) says, and I quote: "None of the arguments are evaluated at macro expansion time".

darioo
  • 46,442
  • 10
  • 75
  • 103
3

Your presumption is correct. Defun is commonly a special form or macro

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
3

You can download here a basic introduction into Lisp:

Common Lisp: A Gentle Introduction to Symbolic Computation, by David S. Touretzky.

Lisp and especially Common Lisp has several Lisp forms:

  • function calls

  • macro calls

  • special forms

DEFUN is a macro. Thus the macro defines which parts are evaluated and which not. For ANSI Common Lisp this is defined in the standard and implemented by the DEFUN macro.

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
2

defun is not a function, but a special form (or boils down to one), and for these, evaluation mechanics are different. Similar examples would be if, where one of the arguments is even discarded entirely without being evaluated at all!

Ulrich Schwarz
  • 7,598
  • 1
  • 36
  • 48