Juan Reynoso Elias
En 2018-01-17 17:43:31

Defun and Lambda



DEFUN defines a function with name
 

You can define a named function using the DEFUN form:
 
(defun sum (x y)
  (+ x y))

 
The defun form has the following arguments:

  • The name of the function: sum
  • A list of argument names: x y
  • The body of the function: (+ x y)

DEFUN returns the name of the defined function, so we have a sum as function.

Now we are going to review the lambda.
 
 
LAMBDA defines anonymous functions
 
Lisp lets you create an unnamed, or anonymous, function using the LAMBDA form:

(lambda (x y)
  (+ x y))


The lambda form has the following arguments:

  • A list of the arguments names: x y
  • The body of the lambda: (+ x y)

I ask me, how can I call or use the lambda?, well I could do this:
 
((lambda (x y)
  (+ x y)) 1 2)


or

(funcall (lambda (x y)
  (+ x y)) 1 2)


Other examples:

 
I have a list like this (1 2 3 4 5), so I want to add 1 all of them, then the result will be (2 3 4 5 6)
 
How can I do that?
 
We are going to use mapcar with a lambda:
 
(mapcar (lambda (x) (+ x 1)) '(1 2 3 4 5))

 
Now I have a list like this: ((9 2 7 5) (7 2 0 9) (10 1 0 21 15 )), so I want to sort the list like this ((2 5 7 9) (0 2 7
9) (0 1 10 15 21))
 
(mapcar (lambda (x) (sort x #'< )) '((9 2 7 5) (7 2 0 9) (10 1 0 21 15 )))


 
También te podría interesar