Juan Reynoso Elias
En 2017-04-26 10:49:24

Function closures


A closure is a function with its own private environment. The environment's bindings may not be used or modified-except by the associated function. The environment is used to define the values of free variables (Le., variables in the function body which are not in the variable list).


Creating and using closures


We'll define a function ADDER which given a number-say 1 -returns a new function which remembers the given number. This new function is the closure ADD1.


;; define a function

(defun adder (x)
  (lambda (y)
    (+ x y)))


;; the closure

(setf add1 (adder 1))


Now we are using the closure:

;; using the closure

(mapcar add1 '(1 2 3))


;;result

(2 3 4)