Re: Metaprogramming using Scheme
- From: andreuri2000@xxxxxxxxx
- Date: 30 Jan 2006 08:01:27 -0800
Jonathan Bartlett wrote:
> Wrong as in "bad style" or "leads to undefined/unintended results"?
Wrong as in "leads to undefined/unintended results". The identifiers
are not introduced correctly. The example:
(define-syntax with-math-defines
(lambda (x)
(syntax-case x ()
((with-math-defines expression)
(with-syntax
((expr
(datum->syntax-object
(syntax k)
`(let ( (pi 3.14) (e 2.72))
,(syntax-object->datum (syntax expression))))))
(syntax expr))))))
has two things wrong with it. First, the k in (syntax k) should
refer to the context where the macro call occurred (otherwise the
macro will break when using modules, etc.). Fixing this, let's write:
(define-syntax with-math-defines
(lambda (x)
(syntax-case x ()
((k expression)
(with-syntax
((expr
(datum->syntax-object
(syntax k)
`(let ( (pi 3.14) (e 2.72))
,(syntax-object->datum (syntax expression))))))
(syntax expr))))))
But now we have lost referential transparency. For example,
the following give errors:
(let ((let 0))
(with-math-defines
(* pi e)))
==> procedure application: expected procedure,
given: 3.141592653589793
(let ((x 0))
(let-syntax ((bar (syntax-rules ()
((_ exp)
(with-math-defines exp)))))
(let ((x 1))
(let-syntax ((foo (syntax-rules ()
((_) (bar x)))))
(foo)))))
==> 0 instead of the correct answer 1
The correct way to introduce these variables, while preserving
hygiene and referential transparency, is
(define-syntax with-math-defines
(lambda (x)
(syntax-case x ()
((k expression)
(with-syntax
((pi (datum->syntax-object (syntax k) 'pi))
(e (datum->syntax-object (syntax k) 'e)))
(syntax
(let ((pi 3.14) (e 2.72))
expression)))))))
(let ((let 0))
(with-math-defines
(* pi e))) ==> 8.5408
(let ((x 0))
(let-syntax ((bar (syntax-rules ()
((_ exp)
(with-math-defines exp)))))
(let ((x 1))
(let-syntax ((foo (syntax-rules ()
((_) (bar x)))))
(foo))))) ==> 1
Similar considerations apply to the cgi-boilerplate macro.
Regards
Andre
.
- Follow-Ups:
- Re: Metaprogramming using Scheme
- From: Anton van Straaten
- Re: Metaprogramming using Scheme
- References:
- Metaprogramming using Scheme
- From: Bradley J Lucier
- Re: Metaprogramming using Scheme
- From: andreuri2000
- Re: Metaprogramming using Scheme
- From: Jonathan Bartlett
- Metaprogramming using Scheme
- Prev by Date: Re: A mutating definition
- Next by Date: Question about method
- Previous by thread: Re: Metaprogramming using Scheme
- Next by thread: Re: Metaprogramming using Scheme
- Index(es):
Relevant Pages
|