Skip to content

Instantly share code, notes, and snippets.

@MarisaKirisame
Created August 13, 2021 06:29
Show Gist options
  • Save MarisaKirisame/d198da5da3571c9af121c9e764a17ff5 to your computer and use it in GitHub Desktop.
Save MarisaKirisame/d198da5da3571c9af121c9e764a17ff5 to your computer and use it in GitHub Desktop.
module StringMap = Map.Make (String);;
open StringMap;;
type op =
| Add
| Sub
| Mult
| Div;;
type expr =
| Lit of int
| BOp of expr * op * expr
| Var of string
let evalop op l r =
match op with
| Add -> l + r
| Sub -> l - r
| Mult -> l * r
| Div -> l / r;;
let rec interpret e m =
match e with
| Lit n -> n
| BOp (l, op, r) -> evalop op (interpret l m) (interpret r m)
| Var str -> find str m;;
let rec compile e =
match e with
| Lit n -> fun m -> n
| BOp (l, op, r) ->
let
cl = compile l and cop = evalop op and cr = compile r in
fun m -> cop (cl m) (cr m)
| Var str -> find str;;
let x = Var "x";;
let e = BOp ((BOp (x, Mult, (Lit 4))), Add, (BOp (x, Mult, (Lit 2))));;
let m = add "x" 1 empty;;
(interpret e m, compile e m);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment