Advertisement
Guest User

Untitled

a guest
Aug 14th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.59 KB | None | 0 0
  1. type expr =
  2.   | Constant of int
  3.   | Variable of string
  4.   | Add of expr * expr
  5.   | Zero
  6.  
  7. let rec simplify expr =
  8.   let (c, expr) = simplify_acc expr in
  9.   if c = 0 then expr else Add(Constant c, expr)
  10. and simplify_acc = function
  11.   | Constant x -> (x, Zero)
  12.   | Variable v -> (0, Variable v)
  13.   | Add (l, r) -> simplify_add(simplify_acc l, simplify_acc r)
  14.   | Zero -> (0, Zero)
  15. and simplify_add = function
  16.   | ((_, Constant _), _) |(_, (_, Constant _)) -> failwith "no"
  17.   | ((lc, Zero), (rc, v))
  18.   | ((lc, v), (rc, Zero)) -> (lc + rc, v)
  19.   | ((lc, l), (rc, r)) -> (lc + rc, Add(l, r))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement