[racket] Racket macro state reset

From: Paul Ojanen (engineer at alum.mit.edu)
Date: Mon Feb 16 14:36:16 EST 2015



I'm working on a macro that will have mutable state. 

[I'm new to macros in general, and I'm new to pattern matching in Racket and
all things related to syntax functions and objects.  I'm also still learning
about macro expansion, compile time, run time, etc.]


I was surprised that the macro's state is empty when I try to interact with
it from the Interactions Window.  Are all the compile/macro-expansion time
definitions redefined for the Interactions Window?


In the below Interactions Window dialogue, why does (acc) start referring to
a different hashtable than ht2?





Here's my stripped-down code:


#lang racket



  (define ht (make-hash))



(define-syntax (acc stx)

  (syntax-case stx ()

    [(_ (f (fn x) body)) (begin


                           ; Record what was defined within the acc block

                           (hash-set! ht

                                      (syntax->datum (syntax fn))

                                      (syntax->datum (syntax body)))


                           ; Define it in the real evironment

                           #'(f (fn x) body))]


    [(_) (datum->syntax #'acc ht)] ; see what's been recorded



; Define a sqr function


(define (sqr2 x) (* x x))



; Try the sqr function

(sqr2 5)


; See what was recorded by the macro



; Bind a run-time variable to the macro's hashtable

(define ht2 (acc))


--------Interactions Window dialogue


'#hash((sqr2 . (* x x)))

> (sqr2 5)


> (acc) ;the hashtable is empty


> ht2 ;no, it's not

'#hash((sqr2 . (* x x)))

> (acc (define (sqr3 x) (* x x)))

> (acc)

'#hash((sqr3 . (* x x)))

> ht2

'#hash((sqr2 . (* x x)))


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20150216/55dbf6ea/attachment.html>

Posted on the users mailing list.