expression - (* - Expression type - *) type bop = Add | Sub...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
(* --------------------- Expression type ---------------------- *) type bop = Add | Sub | Mul | Div | Pow type uop = Sin | Cos | Ln | Neg type expr = Num of float | Var | BinOp of bop * expr * expr | UnOp of uop * expr (* --------------------- Helper functions ---------------------- *) let fabs n = if (n < 0.0) then -. n else n let string_to_char_list s = let rec helper s lst i = if i<0 then lst else let c = String.get s i in helper s (c::lst) (i-1) in helper s [] (String.length s - 1) (* The precedence of a binary operator. Used in the parse_expr and to_string_smart functions. *) let get_precedence b = match b with | Add -> 3 | Sub -> 3 | Mul -> 2 | Div -> 2 | Pow -> 1 type expr_tokens = Bop of bop | Uop of uop | Nu of float | Va | LParan | RParan | LBrace | RBrace | EOF let recognized_tokens = [|"x";"sin";"cos";"ln"|] let token_exprs = [|Va;Uop(Sin);Uop(Cos);Uop(Ln)|] (* -------------- to_string functions for exprs ------------- *) let bop_to_string b = match b with | Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Pow -> "^" let uop_to_string u =
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
match u with | Sin -> "sin" | Cos -> "cos" | Ln -> "ln" | Neg -> "~" let token_to_string ue = match ue with | Nu n -> string_of_float n | Va -> "x" | Bop b -> bop_to_string b | Uop u -> uop_to_string u | LParan -> "(" | RParan -> ")" | LBrace -> "{" | RBrace -> "}" | EOF -> "EOF" (* A string representation of e. Only adds parentheses when needed to prevent ambiguity. *) let to_string_smart e = let uop_precedence = 4 in let rec helper e parent_precedence minus_or_div = match e with | Num(n) -> if (n >= 0.) then string_of_float n else "~" ^ string_of_float(fabs n) | Var -> "x" | UnOp(u,e1) -> uop_to_string u ^ "(" ^ helper e1 uop_precedence false ^ ")"
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

expression - (* - Expression type - *) type bop = Add | Sub...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online