This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Lambda vs Defun

5 posts · 4412 views

Can someone explain the difference between Lambda and Defun and when to use each one.
I have just been using defun the whole time.

Thanks

Re: Lambda vs Defun

DEFUN does two things. It creates a function, and it attaches it to a name.
LAMBDA creates a function with no name.

So you generally use DEFUN when you want to call the function by name, and LAMBDA when you don't care about the function's name.
In practice, LAMBDA is mostly used for small functions that get passed to other functions like MAP.

Re: Lambda vs Defun

Does lisp care which one you use because I have a function that is not being evaluated ever. No matter where i put it in my code just to test it skips over it. I thought it may need to be a lambda function or something strange like that.
Simply it looks like this.

(defun dosomething(name)
(format t "Your name ~s" name))

(defun noFile()
(if (y-or-n-p "Yes or No")
(format t "You said yes")
(dosomething "Thomas")))

and that dosomething never gets done. I can even put it into the 'yes' part of the if or I have even tried putting it in my 'main' program bit.
And I know it goes into it because a run of it will print the yes bit but whn i say 'no' it does nothing.

Any thoughts?

Thanks

Re: Lambda vs Defun

Try it again. It works for me.
(defun dosomething (name)
   (format t "Your name ~s" name))

(defun noFile ()
   (if (y-or-n-p "Yes or No")
       (format t "You said yes")
       (dosomething "Thomas")))
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

Re: Lambda vs Defun

Probably the reason it "doesn't work" is that the output stream doesn't get flushed: "Your name Thomas" is written to the output, but doesn't appear on your screen until much later (or possibly never, if you're doing something weird like running your function and immediately shutting down your Lisp). Put a call to FORCE-OUTPUT in DOSOMETHING. (But I'm confused if "You said yes" is showing up.)

To the original question: (defun foo (bar) baz) is essentially a macro that expands into (setf (symbol-function 'foo) (lambda (bar) baz)) [plus some implemention-dependent housekeeping stuff, perhaps]; there's no difference.