Next: , Previous: , Up: baselib expressions   [Index]


4.4.2 Procedures

Syntax: lambda ?formals ?body

?formals must be a formal parameter list as described below, and ?body must be as described in baselib bodies.

A lambda evaluates to a procedure. The environment in effect when the lambda is evaluated is remembered as part of the procedure. When the procedure is later called with some arguments, the environment in which the lambda was evaluated is extended by binding the variables in the parameter list to fresh locations, and the resulting argument values are stored in those locations. Then, the expressions in the body of the lambda (which may contain definitions and thus represent a letrec* form) are evaluated sequentially in the extended environment. The results of the last expression in the body are returned as the results of the procedure call.

(lambda (x) (+ x x))      ⇒ a procedure
((lambda (x) (+ x x)) 4)  ⇒ 8

((lambda (x)
   (define (p y)
     (+ y 1))
   (+ (p x) x))
 5) ⇒ 11

(define reverse-subtract
  (lambda (x y) (- y x)))
(reverse-subtract 7 10)         ⇒ 3

(define add4
  (let ((x 4))
    (lambda (y) (+ x y))))
(add4 6)                        ⇒ 10

?formals must have one of the following forms:

(?variable1 …)

The procedure takes a fixed number of arguments; when the procedure is called, the arguments are stored in the bindings of the corresponding variables.

?variable

The procedure takes any number of arguments; when the procedure is called, the sequence of arguments is converted into a newly allocated list, and the list is stored in the binding of the ?variable.

(?variable1?variableN . ?variableN+1)

If a period . precedes the last variable, then the procedure takes n or more arguments, where n is the number of parameters before the period (there must be at least one). The value stored in the binding of the last variable is a newly allocated list of the arguments left over after all the other arguments have been matched up against the other parameters.

((lambda x x) 3 4 5 6)          ⇒ (3 4 5 6)
((lambda (x y . z) z)
 3 4 5 6)                       ⇒ (5 6)

Any ?variable must not appear more than once in ?formals.


Next: , Previous: , Up: baselib expressions   [Index]