This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

On lambda function

6 posts · 2023 views

Here's a function that takes a number N, and returns a function that adds N to its argument (taken from Practical Common Lisp):
(defun add-n (n)
	#'(lambda (x)
		(+ x n)))
My guess was something like this should work:
((add-n 1) 2)
Unfortunately, it doesn't work. Further investigation:
? (functionp 'add-n)
NIL
Now I'm confused. How can I use this add-n properly?

Re: On lambda function

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):
(defun add-n (n)
	#'(lambda (x)
		(+ x n)))
My guess was something like this should work:
((add-n 1) 2)
Unfortunately, it doesn't work. Further investigation:
? (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:
(funcall (add-n 1) 2)
(For details, see information about Lisp-1 vs Lisp-2)

Re: On lambda function

Yeah that works. Thanks for you explanation.

BTW, I did tried this, and also failed:
(funcall #'+(add-n 1) 2)
Probably because add-n is just an anonymous function?

Re: On lambda function

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

BTW, I did tried this, and also failed:
(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).

Re: On lambda function

Ah OK. I think I understand it.

:)