20-CS-4003-001 Organization of Programming Languages Fall 2017
Define-Syntax examples

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

Define-syntax (macros)

(define-syntax doit
  (syntax-rules ()
    ((doit a ...) 
     (letrec ((a (lambda () 'a)) ...)
        (list (a) ...)))))

(define-syntax doit-again
  (syntax-rules ()
    ((doit-again (a n) ...) 
     (letrec ((a (lambda (x) 
                   (if (= x 0) 
                       '() 
                       (cons x (a (- x 1)))))) ...)
       (list (a n) ...)))))
 -  Macro doit expands to the invocation of a procedure of any number of arguments, each being some kind of symbol or sequence of symbols. For each sequence of symbols, the letrec creates a procedure with a name that is taken from the argument list of doit. The body of the lectrec invokes each of those procedures and puts the results in a list which becomes the value of doit. For example:
  prompt> (doit john - mary)
  ;Value 67: (john - mary)

The macro doit-again shows that the names in the argument list can become the names of recursive procedures. In this case the procedures produce a list of decreasing integers beginning with an n that associates with the procedure's name. For example:

  (doit-again (john 3) (jim 4) (jane 5))
  ;Value 33: ((3 2 1) (4 3 2 1) (5 4 3 2 1))