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


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)


val c : int -> expr = <fun>
val v : string -> expr = <fun>
val ( + ) : expr -> expr -> expr = <fun>
val ( - ) : expr -> expr -> expr = <fun>
val ( / ) : expr -> expr -> expr = <fun>
val ( * ) : expr -> expr -> expr = <fun>
val ( ^ ) : expr -> expr -> expr = <fun>

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;;


val print : expr -> string = <fun>
val pretty_print : Format.formatter -> expr -> unit = <fun>

Some examples


In [31]:
let _ = v "a" + v "b"
let _ = c 10 * v "a"
let _ = v "a" ^ (v "b" / c 2)


$$(a+b)$$
$$10 a$$
$$a ^{b/2}$$
- : expr = <expr>
- : expr = <expr>
- : expr = <expr>

In [29]:
let x,y,z = v "x", v "y", v "z" in
(((c 1 + x) * (c 7 - y)) ^ (z + c 2)) / (c 8)


$$(1+x) (7-y) ^{(z+2)}/8$$
- : expr = <expr>

In [ ]: