[back]

Pretty Arithmetic Expressions

type expr
  = Num of int
  | Var of string
  | Add of expr * expr
  | Mul of expr * expr

The type expr represents arithmetic expressions (over addition and multiplication only) with variables.

Implement the function

val string_of_expr : expr -> string

so that string_of_expr e is a string representation of e according to the following rules.

Examples

let _ = assert (string_of_expr (Mul (Num 2, Add (Num 3, Num 4))) = "2 * (3 + 4)")
let _ = assert (string_of_expr (Add (Num 2, Add (Num 3, Num 4))) = "2 + 3 + 4")
let _ = assert (string_of_expr (Add (Mul (Num 2, Num 3), Num 4)) = "2 * 3 + 4")
let _ = assert (string_of_expr (Add (Num (-2), Add (Num (-3), Num 4))) = "-2 + (-3) + 4")
let _ = assert (string_of_expr (Mul (Num (-2), Add (Num (-3), Num 4))) = "-2 * (-3 + 4)")