ce/eval.ml
2022-01-11 01:05:29 +09:00

24 lines
588 B
OCaml

open Ast
let arith f a b =
match a, b with
| Int a, Int b -> Int (f a b)
| _ -> failwith "typecheck failed"
let binop_to_func = function
| Add -> arith Int.add
| Sub -> arith Int.sub
| Mul -> arith Int.mul
| Div -> arith Int.div
let rec eval = function
| Value v -> v
| Binop (l, op, r) ->
let f = binop_to_func op in
f (eval l) (eval r)
| Set_binop_pre (op, l) ->
let l = match eval l with Int n -> n | _ -> failwith "not int" in
Hashtbl.replace Parser.precedence op l;
Unit
| Get_binop_pre op ->
Int (Hashtbl.find Parser.precedence op)