Page 1 of 1

Question about lambda

Posted: Tue May 31, 2011 9:23 pm
by August
On my Lisp journey, there is something about lambda that has been bugging me.

;; This works, as expected.
((lambda (n) (* n n)) 3)

;; This doesn't work, as expected;
(#'(lambda (n) (* n n)) 3)

;; This works, as expected.
(mapcar #'(lambda (n) (* n n)) '(1 2 3))

;; Why does this work also?
(mapcar (lambda (n) (* n n)) '(1 2 3))

I didn't expect this last case to work, assuming that you need to get the function value of the lambda to pass it as an argument.

Re: Question about lambda

Posted: Tue May 31, 2011 10:04 pm
by ramarren
In operator position (as considered by the evaluator) LAMBDA is not treated specially, as it is when it is in a form in function name position (as in the first and third of your examples), but rather as a perfectly standard macro which expands to (function (lambda ...)).

Re: Question about lambda

Posted: Wed Jun 01, 2011 9:57 am
by August
Thanks Ramarren. I guess I need to read through the hyperspec more thoroughly :-)

Style-wise, do people generally use the #' when using lambda as a function argument and when returning a lambda from a function?

Re: Question about lambda

Posted: Wed Jun 01, 2011 10:14 am
by ramarren
I do not believe there is consensus on this. I personally like to use #' to additionally indicate that an anonymous function is returned. Since the LAMBDA macro was added relatively late in the standardisation process this can be considered "old-style", but Practical Common Lisp uses it as well.

Re: Question about lambda

Posted: Wed Jun 01, 2011 10:33 am
by August
OK, thanks much for the help!

Re: Question about lambda

Posted: Sun Jun 05, 2011 5:40 pm
by findinglisp
August wrote:Style-wise, do people generally use the #' when using lambda as a function argument and when returning a lambda from a function?
Generally, yes, people use #'(LAMBDA ...).