Page 1 of 1

Lambda vs Defun

Posted: Tue Sep 11, 2012 9:17 pm
by samohtvii
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

Posted: Tue Sep 11, 2012 9:31 pm
by nuntius
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

Posted: Tue Sep 11, 2012 9:44 pm
by samohtvii
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

Posted: Wed Sep 12, 2012 6:17 am
by Goheeca
Try it again. It works for me.

Code: Select all

(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")))

Re: Lambda vs Defun

Posted: Wed Sep 26, 2012 7:00 pm
by Paul
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.