macrolyte
macrolyte

Reputation: 352

Passing A Function In Common Lisp

I've very new to lisp so please bear with me. The following code is an attempt at what I 'thought' was a way to pass a function, but it appears to be something else:

(defun hello-world () (format t "hello, world!"))                                     
(defun ll (x y) (+ (* 3 y)x))
(defun zz(x)(funcall(λ(x)x)x))
>(zz (hello-world))
>hello, world!NIL
>(zz (ll 3 4))
>15
>(zz 8)
>8

My question(s): Is this an identity function? If not, why? Lastly, why is the last (x) required for the lambda expression? Any canonical source material would be greatly appreciated. Thanks.

Upvotes: 2

Views: 525

Answers (1)

sds
sds

Reputation: 60014

Let me try to analyze your code step by step

(lambda (x) x)

This is a function which takes one argument, binds variable x to it, and returns x, i.e., the identity function.

(funcall (lambda (x) x) x)

This calls the aforementioned identity function on argument x (unrelated to the first two x's in the expression), so this is the same as x.

(defun zz (x) (funcall (lambda (x) x) x))

This defines a new function zz, which, as discussed above, is the identity function.

Look at the values returned by your function calls, e.g.:

(zz (hello-world))
hello, world!NIL

hello-world prints "hello, world!" and returns NIL, which is passed to zz, which, in turn, return its argument intact as NIL.

Upvotes: 2

Related Questions