2016-08-20 78 views
1

假设我在球拍中有一些模块,其中包含非重要的define“覆盖”。该“覆盖”收集有关过程体的信息并将其存储到映射中(编译阶段)。现在我需要在运行时阶段使用收集的信息。直截了当的aproach似乎没有工作:查看阶段0的阶段1计算结果

#lang racket 

(require (for-syntax racket)) 

(define-for-syntax map-that-should-be-used-in-phase-0 (make-hash)) 
(define-for-syntax (fill-in-useful-information n) (hash-set! map-that-should-be-used-in-phase-0 n n)) 

; Suppose that some useful information is collected here and stored into a map 
(define-syntax (fill-in-map stx) 
    (begin 
    (fill-in-useful-information 1) 
    (fill-in-useful-information 2) 
    (syntax/loc stx (displayln "OK, the map is filled, but I cannot see it here")))) 

(define-syntax (print-that-map stx) 
    (syntax/loc stx (displayln map-that-should-be-used-in-phase-0))) ; <-- This can not be compiled 

(fill-in-map) 
(print-that-map) 

我可以在球拍吗?如果是,那么如何?任何提示将非常感激!

+2

我承认,我完全丧失了为什么这个问题被低估了。对我来说这似乎是一个很好的问题。 –

+0

@AlexisKing感谢您的评论,我也想知道为什么。我期望他们解释一下原因。 – dvvrd

回答

2

引用变量的标识符无法编译,但只要它是Racket提供的内置数据结构之一,并且只要它是不可变的,它所指的值就可以。

可以使用quasisyntaxunsyntax将哈希表值粘贴到语法对象中。

> (quasisyntax (foo #,(hash 'a 4 'b 16))) 
#<syntax:5:15 (foo #hash((a . 4) (b . 16)))> 

你可以做同样的事情来从编译时向运行时进行单向通信。

(define-for-syntax (hash->immutable-hash hsh) 
    (make-immutable-hash (hash->list hsh))) 

(define-syntax (print-that-map stx) 
    (quasisyntax/loc stx (displayln #,(hash->immutable-hash map-that-should-be-used-in-phase-0)))) 
+0

非常感谢!这个想法似乎解决了我的问题! – dvvrd