Define a simple type representing expressions
In [11]:
type expr =
| Const of int
| Var of string
| Add of expr * expr
| Sub of expr * expr
| Mul of expr * expr
| Div of expr * expr
| Pow of expr * expr
An api for writing expressions
In [12]:
let c x = Const x
let v x = Var x
let (+) a b = Add(a,b)
let (-) a b = Sub(a,b)
let (/) a b = Div(a,b)
let ( * ) a b = Mul(a,b)
let (^) a b = Pow(a,b)
Basic pretty printing function.
In [27]:
let rec print x =
let open Pervasives in
match x with
| Const i -> string_of_int i
| Var x -> x
| Add(a,b) -> "(" ^ print a ^ "+" ^ print b ^ ")"
| Sub(a,b) -> "(" ^ print a ^ "-" ^ print b ^ ")"
| Mul(a,b) -> print a ^ " " ^ print b
| Div(a,b) -> print a ^ "/" ^ print b
| Pow(a,b) -> print a ^ " ^{" ^ print b ^ "}";;
let pretty_print fmt x =
let open Pervasives in
Iocaml.display "text/html" ("$$" ^ print x ^ "$$");
Format.fprintf fmt "<expr>";;
#install_printer pretty_print;;
Some examples
In [31]:
let _ = v "a" + v "b"
let _ = c 10 * v "a"
let _ = v "a" ^ (v "b" / c 2)
In [29]:
let x,y,z = v "x", v "y", v "z" in
(((c 1 + x) * (c 7 - y)) ^ (z + c 2)) / (c 8)
In [ ]: