Skip to content

Instantly share code, notes, and snippets.

@dannypsnl
Forked from shhyou/0-env.rkt
Created February 18, 2021 13:07
Show Gist options
  • Select an option

  • Save dannypsnl/3ae083d3d59e23280bd41a47fbd7e0f4 to your computer and use it in GitHub Desktop.

Select an option

Save dannypsnl/3ae083d3d59e23280bd41a47fbd7e0f4 to your computer and use it in GitHub Desktop.
Compilation-time Environment
#lang racket/base
(require (for-syntax racket/base
"env.rkt"))
(provide my-fun
your-fun)
(define (my-fun a b)
(+ a b))
(define (your-fun c)
(- c))
;; https://docs.racket-lang.org/syntax/syntax-helpers.html#%28part._.Dictionaries_for_free-identifier~3d_%29
;; Must be placed after the definition of my-fun
(begin-for-syntax
(env-add! #'my-fun "my-fun from add.rkt")
(env-add! #'your-fun "your-fun from add.rkt"))
;; Exporting free identifier table operations that close over a global map
#lang racket/base
(require syntax/id-table)
(provide env-ref env-has-id? env-add!)
(define id-table (make-free-id-table))
(define (env-ref id)
(free-id-table-ref id-table id))
(define (env-has-id? id)
(with-handlers ([exn:fail? (λ (e) #f)])
(free-id-table-ref id-table id)
#t))
(define (env-add! id value)
(free-id-table-set! id-table id value))
#lang racket/base
(require (for-syntax racket/base
"env.rkt")
"add.rkt")
(provide my-fun)
(begin-for-syntax
(printf "mul.rkt: your-fun is: ~s\n" (env-ref #'your-fun)))
(define (my-fun a b)
(* a (your-fun b)))
;; https://docs.racket-lang.org/syntax/syntax-helpers.html#%28part._.Dictionaries_for_free-identifier~3d_%29
;; Must be placed after the definition of my-fun
(begin-for-syntax
(env-add! #'my-fun "my-fun from mul.rkt"))
;; Dependency:
;; add depends on {env}
;; mul depends on {add,env}
;; use depends on {mul,add,env}
#lang racket/base
(require (for-syntax racket/base
"env.rkt")
(only-in "add.rkt" my-fun)
(rename-in "mul.rkt" [my-fun mul:my-fun]))
(begin-for-syntax
(printf "use.rkt: my-fun = ~s\n" (env-ref #'my-fun))
(printf "use.rkt: has-key?(your-fun) = ~s\n" (env-has-id? #'your-fun)) ;; => #f
(printf "use.rkt: mul:my-fun = ~s\n" (env-ref #'mul:my-fun))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment