Lambda vs Defun

Discussion of Common Lisp

Lambda vs Defun

Postby 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
samohtvii
 
Posts: 12
Joined: Thu Aug 23, 2012 11:49 pm

Re: Lambda vs Defun

Postby 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.
User avatar
nuntius
 
Posts: 498
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA

Re: Lambda vs Defun

Postby 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
samohtvii
 
Posts: 12
Joined: Thu Aug 23, 2012 11:49 pm

Re: Lambda vs Defun

Postby 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).
User avatar
Goheeca
 
Posts: 199
Joined: Thu May 10, 2012 12:54 pm

Re: Lambda vs Defun

Postby 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.
Paul
 
Posts: 106
Joined: Tue Jun 02, 2009 6:00 am


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 3 guests