Skip to content

Instantly share code, notes, and snippets.

@jbclements
Created April 24, 2020 17:18
Show Gist options
  • Save jbclements/7b9a850ea5af90fb4209c244a01bb8b0 to your computer and use it in GitHub Desktop.
Save jbclements/7b9a850ea5af90fb4209c244a01bb8b0 to your computer and use it in GitHub Desktop.
#lang typed/racket
(require typed/rackunit)
;; an S-expression is one of:
;; a number
;; a string
;; a boolean
;; a symbol, or
;; (list S-expression ...)
;; concrete syntax of TL
"a string"
"abc"
"def"
'{"abc" + "def"} ; => "abcdef"
'{{"a" + "b"} + "cdef"}
'{"**" around "abc"} ; => "**abc**"
;; abstract syntax of TL
(define-type ExprC (U StrAppdC StrC IdC AppC))
(struct StrC ([s : String]) #:transparent)
(struct IdC ([var : Symbol]) #:transparent)
(struct StrAppdC ([l : ExprC] [r : ExprC]) #:transparent)
(struct AppC ([fun : Symbol] [arg : ExprC]) #:transparent)
(struct FundefC ([name : Symbol] [param : Symbol] [body : ExprC]))
;; parse concrete stx of
(define (parse [s : Sexp]) : ExprC
(match s
[(? string? str) (StrC str)]
[(list a '+ c) (StrAppdC (parse a) (parse c))]))
(check-equal? (parse '"abc")
(StrC "abc"))
(check-equal? (parse '{{"a" + "b"} + "cdef"})
(StrAppdC (StrAppdC (StrC "a")
(StrC "b"))
(StrC "cdef")))
;; interp a function in TL
(define (interp [e : ExprC] [fns : (Listof FundefC)]) : String
(match e
[(StrC s) s]
[(StrAppdC l r) (string-append (interp l) (interp r))]
[(IdC var) (error ...)]
[(AppC f a)
(define fn (fun-lookup f fns))
(match fn
[(FundefC name param body)
(define argval (interp a fns))
(interp (subst param argval body) fns)])]
))
#|
def g(x):
return x + y
g(7)
|#
(check-equal? (interp (StrC "abc")) "abc")
(check-equal? (interp (StrAppdC (StrAppdC (StrC "a")
(StrC "b"))
(StrC "cdef")))
"abcdef")
;; map a program to an output
(define (top-interp [s : Sexp]) : String
(interp (desugar (parse s))))
(top-interp '{"a" + {{"d" + "arj"} + "mwnop"}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment