Skip to content

Instantly share code, notes, and snippets.

@burakemir
Created September 25, 2021 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burakemir/3c005e9908b40af7921a4ec02bbc76e7 to your computer and use it in GitHub Desktop.
Save burakemir/3c005e9908b40af7921a4ec02bbc76e7 to your computer and use it in GitHub Desktop.
Silly example to demonstrate evaluating at compile-time and runtime
#lang reader "test-lang-reader.rkt"
(+ 1 2)
we consider the program (begin (+ 1 2))
the compile-time result is: 3
the run-time result is: 3
#lang racket
(provide (rename-out [literal-read read]
[literal-read-syntax read-syntax]))
(define (literal-read in)
(syntax->datum
(literal-read-syntax #f in)))
(define ns (make-base-namespace))
(define (eval-all exps)
(for/list ([exp exps])
(eval exp ns)))
(define (literal-read-syntax src in)
(let* ([exps (port->list read in)] ;; read the input into an s-expression list.
[res (cons 'begin (eval-all exps))] ;; evaluate all exps, at compile time.
[program-exp (cons 'begin exps)]) ;; prepare for evaluating at runtime
;; with-syntax calls datum->syntax for us.
;; we need to produce a syntax-object, after all.
(with-syntax ([program program-exp])
(with-syntax ([result res])
#`(module anything racket
(displayln (format "we consider the program ~a" (quote program)))
(displayln (format "the compile-time result is: ~a" result))
(displayln (format "the run-time result is: ~a" (begin program))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment