Created
September 25, 2021 19:02
-
-
Save burakemir/3c005e9908b40af7921a4ec02bbc76e7 to your computer and use it in GitHub Desktop.
Silly example to demonstrate evaluating at compile-time and runtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang reader "test-lang-reader.rkt" | |
(+ 1 2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
we consider the program (begin (+ 1 2)) | |
the compile-time result is: 3 | |
the run-time result is: 3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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