Macros and expand

Pondering the philosophy behind the language
Locked
jsmall
Posts: 26
Joined: Mon Sep 20, 2004 1:44 am

Macros and expand

Post by jsmall »

I'm trying to understand the proper use of
expand with macros.

So I define the macro "expand-let"
with the following semantics.

(expand-let '(x y z) (x 1) (y 2) (z 3))

"expands" to the equivalent of

(let ((x 1)(y 2)(z 3))
(expand '(x y z) 'x 'y 'z))

returning

(1 2 3)

The following is my implementation of this semantics

(define (keys alist)
(map (fn (pair) (first pair)) alist))

(define (bindings alist)
(map (fn (pair) (cons (first pair) (eval (last pair)))) alist))

(define-macro (expand-let expr)
(let ((ks (keys (rest (args))))
(bs (bindings (rest (args)))))
(eval (expand '(let bs
(apply expand (cons (eval expr) (quote ks))))
'ks 'bs))))

Is the above definition of expand-let reasonable
or is it poorly constructed?

(I have a follow up example/question that builds on nested
macros if this is okay thus far.)

Thanks.

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

Nice idea the 'expand-let' and nicely implemented. This one follows a similar idea as yours, but collapses everythig into one function. Less readable but smaller:

Code: Select all

(define-macro (expand-let )
  (eval (append (list 'let (rest (args))) 
                (list (cons 'expand 
                             (append (list (first (args))) 
                             (map quote (map first (rest (args))))))))))

(expand-let '(x y z) (x 1) (y (+ 1 1)) (z 3)) => (1 2 3)
Lutz

Locked