
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?

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

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?

Yes, that looks promising - thanks!

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)

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

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.

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