badkins
2021-12-24 17:05:31

I have a file of instructions that I would like to compile into a Racket program. For example: add x y mul y z compiled to: (set! x (+ x y)) (set! y (* y z)) I can easily do this by simply reading the input file and writing the output file, but it seems like Racket, with its emphasis on language oriented programming, might have some better options than just input-file -> compiler -> output-file. If I do the approach above, I suppose I could then dynamically require the resulting file, but that still seems a bit “hacky”. Is there a better macro-oriented approach? For example, something analogous to how include-template compiles a web page?


badkins
2021-12-24 17:06:09

cc: @ben.knoble (I don’t think this is a spoiler since it’s so general :) )


ben.knoble
2021-12-24 17:17:54

Perhaps something like https://github.com/mbutterick/aoc-racket/blob/4d5f19b410ccb23230d3c1dbae58bceffff8adc6/day07.rkt#L47 where a macro expands to (a) parse the file and (b) generate whatever code you wanted?


badkins
2021-12-24 17:21:32

Yes, that looks promising - thanks!


popa.bogdanp
2021-12-24 17:23:08

You can compile your code to s-expressions that define a function, eval those sexprs under a new namespace then extract the defined function from that namespace. Something like:

(define f (parameterize ([current-namespace (make-base-namespace)]) (eval `(define (f x) (+ x 1))) (namespace-variable-value 'f))) (f 1)


badkins
2021-12-24 17:24:26

I suppose one advantage of the more traditional approach above is that you’d have a regular Racket file afterward for easier testing/debugging.


badkins
2021-12-24 17:52:03

I’m trying to get something like the following to work: #lang racket (define x #f) (define (set-var sym val) (eval `(set! ,sym ,val))) (set-var 'x 7) x but I don’t quite understand namespaces.


badkins
2021-12-24 18:07:39

found it! #lang racket (define-namespace-anchor a) (define ns (namespace-anchor->namespace a)) (define x #f) (define (set-var sym val) (eval `(set! ,sym ,val) ns)) (set-var 'x 7) x