Next: , Previous: , Up: scheme overview   [Index]


3.1.11 Derived forms and macros

Many of the special forms specified in this report can be translated into more basic special forms. For example, a let expression can be translated into a procedure call and a lambda expression. The following two expressions are equivalent:

(let ((x 23)
      (y 42))
  (+ x y))
⇒ 65

((lambda (x y) (+ x y)) 23 42)
⇒ 65

Special forms like let expressions are called derived forms because their semantics can be derived from that of other kinds of forms by a syntactic transformation. Some procedure definitions are also derived forms. The following two definitions are equivalent:

(define (f x)
  (+ x 42))

(define f
  (lambda (x)
    (+ x 42)))

In Scheme, it is possible for a program to create its own derived forms by binding syntactic keywords to macros:

(define-syntax def
  (syntax-rules ()
    ((def f (p ...) body)
     (define (f p ...)
       body))))

(def f (x)
  (+ x 42))

The define-syntax construct specifies that a parenthesized structure matching the pattern (def f (p ...) body), where ‘f’, ‘p’, and ‘body’ are pattern variables, is translated to (define (f p ...) body). Thus, the ‘def’ form appearing in the example gets translated to:

(define (f x)
  (+ x 42))

The ability to create new syntactic keywords makes Scheme extremely flexible and expressive, allowing many of the features built into other languages to be derived forms in Scheme.