Monday, November 23, 2009

Scheme - let-syntax

It took me some time to understand what let-syntax does. After
spending much time on the net search for information, I finally
figured it out. let-syntax is the let counterpart of define-syntax.

What does that mean? It means you create a macro that is lexically
bound. That means, let-syntax acts just like let, but it works on
syntax rather than variables. This means we can use let-syntax to
create localized macros. Consider this example..

(import (rnrs))

(define (hw n)
(display n)
(newline))

(let-syntax ((hw
(syntax-rules ()
((_ 0) (begin
(display "Hello World")
(newline)))
((_ n) (begin
(display "Goodbye World")
(newline))))))
(begin
(hw 0)
(hw 1)))

(hw 0)
(hw 1)

The (hw 0) and (hw 1) inside let-syntax end up printing "Hello World"
and "Goodbye World", whereas the (hw 0) and (hw 1) outside the scope,
print 0 and 1.

No comments: