Skip to content

Instantly share code, notes, and snippets.

@takahisa
Created August 7, 2017 01:36
Show Gist options
  • Save takahisa/7d2d4fb4b2b7f5e47c68735c551b05f1 to your computer and use it in GitHub Desktop.
Save takahisa/7d2d4fb4b2b7f5e47c68735c551b05f1 to your computer and use it in GitHub Desktop.
open-recursion
module Eval_base = struct
let eval eval_rec = function
| `Int n -> n
| _ ->
failwith "unknown expression"
let show show_rec = function
| `Int n -> string_of_int n
| _ ->
failwith "unknown expression"
end
module Eval_add = struct
let eval eval_rec = function
| `Add (e0, e1) -> eval_rec e0 + eval_rec e1
| e -> eval_rec e
let show show_rec = function
| `Add (e0, e1) -> Printf.sprintf "(%s + %s)" (show_rec e0) (show_rec e1)
| e -> show_rec e
end
module Eval_sub = struct
let eval eval_rec = function
| `Sub (e0, e1) -> eval_rec e0 - eval_rec e1
| e -> eval_rec e
let show show_rec = function
| `Sub (e0, e1) -> Printf.sprintf "(%s - %s)" (show_rec e0) (show_rec e1)
| e -> show_rec e
end
module Eval = struct
let rec eval e = Eval_sub.eval (Eval_add.eval (Eval_base.eval eval)) e
let rec show e = Eval_sub.show (Eval_add.show (Eval_base.show show)) e
end
module Eval_example = struct
open Eval
let res0 = eval (`Sub (`Add (`Int 1, `Int 2), `Int 3));;
let res1 = show (`Sub (`Add (`Int 1, `Int 2), `Int 3));;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment