4.2. Lambda


4.2. Lambda

(lambda formals exp1 exp2 ...)

syntax

returns: a procedure

The lambda syntactic form is used to create procedures. Any operation that creates a procedure or establishes local variable bindings is ultimately defined in terms of lambda.

The variables in formals are the formal parameters of the procedure, and the sequence of expressions exp1 exp2 is its body.

The body may begin with a sequence of definitions, in which case the established bindings are local to the procedure. If definitions are present, the body is replaced by a letrec expression formed from the definitions and the remaining expressions. Consult Section 3.5 or Section 4.4 for more details. The remainder of this discussion of lambda assumes that this transformation has taken place, if necessary, so that the body is a sequence of expressions without definitions.

When the procedure is created, the bindings of all variables occurring free within the body, excluding the formal parameters, are retained with the procedure. Subsequently, whenever the procedure is applied to a sequence of actual parameters, the formal parameters are bound to the actual parameters, the retained bindings are restored, and the body is evaluated.

Upon application, the formal parameters defined by formals are bound to the actual parameters as follows.

  • If formals is a proper list of variables, e.g., (x y z), each variable is bound to the corresponding actual parameter. It is an error if too few or too many actual parameters are supplied.

  • If formals is a single variable (not in a list), e.g., z, it is bound to a list of the actual parameters.

  • If formals is an improper list of variables terminated by a variable, e.g., (x y . z), each variable but the last is bound to the corresponding actual parameter. The last variable is bound to a list of the remaining actual parameters. It is an error if too few actual parameters are supplied.

When the body is evaluated, the expressions exp1 exp2 are evaluated in sequence. The value of the last expression is the value of the procedure.

Procedures do not have a printed representation in the usual sense. Scheme systems print procedures in different ways; this book uses the notation #<procedure>.

 (lambda (x) (+ x 3))  #<procedure> ((lambda (x) (+ x 3)) 7)  10 ((lambda (x y) (* x (+ x y))) 7 13)  140 ((lambda (f x) (f x x)) + 11)  22 ((lambda () (+ 3 4)))  7 ((lambda (x . y) (list x y))  28 37)  (28 (37)) ((lambda (x . y) (list x y))  28 37 47 28)  (28 (37 47 28)) ((lambda (x y . z) (list x y z))  1 2 3 4)  (1 2 (3 4)) ((lambda x x) 7 13)  (7 13) 




The Scheme Programming Language
The Scheme Programming Language
ISBN: 026251298X
EAN: 2147483647
Year: 2003
Pages: 98

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net