[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.6 Binding constructs

Special Form: let ((var expr) ...) body ...
Special Form: let* ((var expr) ...) body ...
Special Form: letrec ((var expr) ...) body ...
[R5RS] Creates a local scope where var ... are bound to the value of expr ..., then evaluates body .... vars must be symbols, and there shouldn't be a duplication. The value(s) of the last expression of body ... becomes the value(s) of this form.

The three forms differ in terms of the scope exprs are evaluated. Let evaluates exprs before (outside of) let form. Let* evaluates exprs in the scope where vars before it are bound. Letrec evaluates exprs in the environment where vars are already bound (to an undefined value, initially). letrec is necessary to define mutually recursive local procedures.
 
(define x 'top-x)

(let  ((x 3) (y x)) (cons x y)) => (3 . top-x)
(let* ((x 3) (y x)) (cons x y)) => (3 . 3)

(let ((cons (lambda (a b) (+ a b)))
      (list (lambda (a b) (cons a (cons b 0)))))
  (list 1 2))  => (1 2 . 0)

(letrec ((cons (lambda (a b) (+ a b)))
         (list (lambda (a b) (cons a (cons b 0)))))
  (list 1 2))  => 3

Macro: let1 var expr body ...
A convenient macro when you have only one variable. Expanded as follows.

 
(let ((var expr)) body ...)

Special Form: receive formals expression body ...
[SRFI-8] This is the way to receive multiple values. Formals can be a (maybe-improper) list of symbols. Expression is evaluated, and the returned value(s) are bound to formals like the binding of lambda formals, then body ... are evaluated.

 
(define (divrem n m)
  (values (quotient n m) (remainder n m)))

(receive (q r) (divrem 13 4) (list q r))
  => (3 1)

(receive all (divrem 13 4) all)
  => (3 1)

(receive (q . rest) (divrem 13 4) (list q rest)
  => (3 (1))

See also call-with-values in 6.15.4 Multiple values which is the procedural equivalent of receive. You can use define-values (See section 4.10 Definitions) to bind multiple values to the toplevel variables simultaneously. Also let-values and let*-values in SRFI-11 (10.6 srfi-11 - Let-values) provides let-like syntax with multiple values.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Ken Dickey on November, 28 2002 using texi2html