-
-
Save jbclements/4f1f82a2f8eea20b522c350fac25a57a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 typed/racket | |
(require typed/rackunit) | |
;; an Sexp is one of | |
;; - a number, | |
;; - a symbol, | |
;; - a string, | |
;; - a boolean, or | |
;; - a list of zero or more Sexps | |
;; concrete syntax | |
'"abc" | |
'"dfe" | |
'"aaaaaaa" | |
'{"abc" + "def"} | |
'{{"a" + "b"} + "cdef"} ;; ==> "abcdef" | |
;; abstract syntax | |
(define-type ExprS (U StrS StrAppS)) | |
(struct StrS ([str : String]) #:transparent) | |
(struct StrAppS ([l : ExprS] [r : ExprS]) #:transparent) | |
(define-type ExprC (U StrC StrAppC)) | |
(struct StrC ([str : String]) #:transparent) | |
(struct StrAppC ([l : ExprC] [r : ExprC]) #:transparent) | |
;; abstract syntax examples | |
(StrC "abc") | |
(StrAppC (StrAppC (StrC "a") (StrC "b")) (StrC "cdef")) | |
;; parse the concrete stx of TL | |
(define (parse [prog : Sexp]) : ExprC | |
(match prog | |
[(? string? s) (StrC s)] | |
[(list a '+ c) (StrAppC (parse a) (parse c))])) | |
(check-equal? (parse "abc") (StrC "abc")) | |
(check-equal? (parse '{{"a" + "b"} + "cdef"}) | |
(StrAppC (StrAppC (StrC "a") (StrC "b")) | |
(StrC "cdef"))) | |
;; interpret a TL AST | |
(define (interp [e : ExprC]) : String | |
(match e | |
[(StrC s) s] | |
[(StrAppC l r) (string-append (interp l) (interp r))])) | |
(check-equal? (interp (StrC "abc")) "abc") | |
(check-equal? (interp (StrAppC (StrAppC (StrC "a") (StrC "b")) (StrC "cdef"))) | |
"abcdef") | |
;; run a TL program | |
(define (top-interp [prog : Sexp]) : String | |
(interp (desugar (parse prog)))) | |
(top-interp '{"zzz" + {{"a" + "b"} + "cdef"}}) | |
'{"'" around "abc"} ;; => "'abc'" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment