On lambda function

Discussion of Common Lisp

On lambda function

Postby anta40 » Mon Jul 06, 2009 11:34 pm

Here's a function that takes a number N, and returns a function that adds N to its argument (taken from Practical Common Lisp):
Code: Select all
(defun add-n (n)
   #'(lambda (x)
      (+ x n)))


My guess was something like this should work:
Code: Select all
((add-n 1) 2)


Unfortunately, it doesn't work. Further investigation:
Code: Select all
? (functionp 'add-n)
NIL


Now I'm confused. How can I use this add-n properly?
anta40
 
Posts: 18
Joined: Fri Oct 10, 2008 10:27 pm

Re: On lambda function

Postby dmitry_vk » Tue Jul 07, 2009 1:17 am

anta40 wrote:Here's a function that takes a number N, and returns a function that adds N to its argument (taken from Practical Common Lisp):
Code: Select all
(defun add-n (n)
   #'(lambda (x)
      (+ x n)))


My guess was something like this should work:
Code: Select all
((add-n 1) 2)


Unfortunately, it doesn't work. Further investigation:
Code: Select all
? (functionp 'add-n)
NIL


Now I'm confused. How can I use this add-n properly?

(first, it's not a lambda function. It is either anonymous function or a lambda expression)

'add-n is a symbol. But #'add-n is a function. (add-n 10) is also a function.
The expression ((add-n 1) 2) works in scheme, in common lisp you should use funcall:
Code: Select all
(funcall (add-n 1) 2)

(For details, see information about Lisp-1 vs Lisp-2)
dmitry_vk
 
Posts: 96
Joined: Sat Jun 28, 2008 8:01 am
Location: Russia, Kazan

Re: On lambda function

Postby anta40 » Tue Jul 07, 2009 4:19 am

Yeah that works. Thanks for you explanation.

BTW, I did tried this, and also failed:
Code: Select all
(funcall #'+(add-n 1) 2)


Probably because add-n is just an anonymous function?
anta40
 
Posts: 18
Joined: Fri Oct 10, 2008 10:27 pm

Re: On lambda function

Postby dmitry_vk » Tue Jul 07, 2009 4:38 am

anta40 wrote:Yeah that works. Thanks for you explanation.

BTW, I did tried this, and also failed:
Code: Select all
(funcall #'+(add-n 1) 2)


Probably because add-n is just an anonymous function?

Add-n is a function. (add-n 1) is an expression that when evaluated returns the anonymous function.
#' is a "function designator". You should use it only in two cases: #'x where x is a symbol or #'(lambda (args) body).
dmitry_vk
 
Posts: 96
Joined: Sat Jun 28, 2008 8:01 am
Location: Russia, Kazan

Re: On lambda function

Postby anta40 » Tue Jul 07, 2009 5:04 am

Ah OK. I think I understand it.

:)
anta40
 
Posts: 18
Joined: Fri Oct 10, 2008 10:27 pm

Re: On lambda function

Postby nuntius » Tue Jul 07, 2009 10:49 am

You won't fully understand until you read the following snippet of the spec.
http://www.lispworks.com/documentation/ ... 02_dhb.htm
User avatar
nuntius
 
Posts: 498
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA


Return to Common Lisp

Who is online

Users browsing this forum: Yahoo [Bot] and 1 guest

cron