Lambda vs Defun

Discussion of Common Lisp
Post Reply
samohtvii
Posts: 12
Joined: Thu Aug 23, 2012 11:49 pm

Lambda vs Defun

Post by samohtvii » Tue Sep 11, 2012 9:17 pm

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

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Lambda vs Defun

Post by nuntius » Tue Sep 11, 2012 9:31 pm

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.

samohtvii
Posts: 12
Joined: Thu Aug 23, 2012 11:49 pm

Re: Lambda vs Defun

Post by samohtvii » Tue Sep 11, 2012 9:44 pm

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

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: Lambda vs Defun

Post by Goheeca » Wed Sep 12, 2012 6:17 am

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

Paul
Posts: 106
Joined: Tue Jun 02, 2009 6:00 am

Re: Lambda vs Defun

Post by Paul » Wed Sep 26, 2012 7:00 pm

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.

Post Reply