User Tools

Site Tools


ch2_1_lambda

This is an old revision of the document!


LAMBDA

LAMBDA form returns an unnamed function object. Apart from that, syntax is the same as DEFUN. First argument must be a list of parameters (symbols) of the function, the symbols are not evaluated. Second argument is optional description string. If the second argument is not string, it is considered first form of the function body. Any other parameters are to LAMBDA are stored as the function body.

>((lambda (a b) (+ a b)) 3 5)   ; unnamed function for adding 2 numbers
8                

In this example we have created unnamed function object in the first position of the whole form, so it gets applied to the numbers 3 and 5.

The function objects created by the LAMBDA forms can be stored somewhere and called later without the need for a name.

>(setq ops (cons             ; define symbol OPS and its value will be a cons-cell
   (lambda (a b) (+ a b))     ; function for addition is in the CAR
   (lambda (a b) (- a b)) )   ; function for subtraction is in the CDR
(#<user-defined lambda> . #<user-defined lambda>)
 
>((car ops) 4 7)             ; using the adding function
11
 
>((cdr op) 4 7)              ; using the subtraction
-3

The functions created by LAMBDA have lexical closure just like named functions.

ch2_1_lambda.1625673708.txt.gz · Last modified: 2021/07/07 10:01 by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki