4.4. Variable Definitions


4.4. Variable Definitions

(define var exp)

syntax

(define (var0 var1 ...) exp1 exp2 ...)

syntax

(define (var0 . varr) exp1 exp2 ...)

syntax

(define (var0 var1 var2 ... . varr) exp1 exp2 ...)

syntax

returns: unspecified

In the first form, define creates a new binding of var to the value of exp. The remaining are shorthand forms for binding variables to procedures; they are identical to the following definition in terms of lambda.

 (define var   (lambda formals     exp1 exp2 ...)) 

where formals is (var1 ), varr, or (var1 var2 . varr) for the second, third, and fourth define formats.

Definitions often appear at "top level," i.e., outside the scope of any lambda or any form derived from lambda, such as let, let*, or letrec. A variable bound at top level is visible within any expression typed at the keyboard or loaded from a file, except where shadowed by a local binding.

Definitions may also appear at the front of a lambda body or body of any form derived from lambda. These internal definitions must precede the expressions in the body. Any lambda expression whose body begins with definitions may be transformed into an equivalent lambda expression without such definitions, by rewriting the body as a letrec expression. That is, a lambda expression of the form

 (lambda formals   (define var val) ...   exp1 exp2 ...) 

may be expressed in the equivalent form below.

 (lambda formals   (letrec ((var val) ...)     exp1 exp2 ...)) 

Although this shows the transformation for the first and simpler form of definition, either form may appear within a lambda body.

Syntax definitions may appear along with variable definitions wherever variable definitions may appear; see Chapter 8.

 (define x 3) x  3 (define f   (lambda (x y)     (* (+ x y) 2))) (f 5 4)  18 (define (sum-of-squares x y)   (+ (* x x) (* y y))) (sum-of-squares 3 4)  25 (define f   (lambda (x)     (+ x 1))) (let ((x 2))   (define f     (lambda (y)       (+ y x)))   (f 3))  5 (f 3)  4 

A set of definitions may be grouped by enclosing them in a begin form. Definitions grouped in this manner may appear wherever ordinary variable and syntax definitions may appear. They are treated as if written separately, i.e., without the enclosing begin form. This feature allows syntactic extensions to expand into groups of definitions.

 (define-syntax multi-define-syntax   (syntax-rules ()     (( (var exp) ...)      (begin        (define-syntax var exp)         ...)))) (let ()   (define plus     (lambda (x y)         (if (zero? x)             y             (plus (sub1 x) (add1 y)))))   (multi-define-syntax     (add1 (syntax-rules () (( e) (+ e 1))))     (sub1 (syntax-rules () (( e) (- e 1)))))   (plus 7 8))  15 




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