File: expr01use_variant.ml

package info (click to toggle)
ocaml-visitors 20200210-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,896 kB
  • sloc: ml: 4,077; makefile: 44; sh: 18
file content (20 lines) | stat: -rw-r--r-- 592 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
open Expr01

let optimize : expr -> expr =
  let o = object(self)
    inherit [_] map
    method! visit_EAdd env e1 e2 =
      match self#visit_expr env e1, self#visit_expr env e2 with
      | EConst 0, e
      | e, EConst 0 -> e
      | e1, e2      -> EAdd (e1, e2)
  end in
  o # visit_expr ()

let z e = EAdd (e, EConst 0)

let () =
  assert (optimize (z (EConst 1)) = EConst 1);
  assert (optimize (z (z (EConst 1))) = EConst 1);
  assert (optimize (EAdd (EConst 1, EConst 1)) = EAdd (EConst 1, EConst 1));
  assert (optimize (EAdd (z (EConst 1), EConst 1)) = EAdd (EConst 1, EConst 1));