-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expression.fs
27 lines (24 loc) · 1.01 KB
/
Expression.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module Expression
type Expr =
| Int of int32
| Parentheses of Expr
| Plus of Expr * Expr
| Times of Expr * Expr
| Divide of Expr * Expr
| Minus of Expr * Expr
let rec compileExpr (e: Expr) =
match e with
| Parentheses e -> compileExpr e |> sprintf "(%s)"
| Plus (l, r) -> (compileExpr l, compileExpr r) ||> sprintf "(%s + %s)"
| Times (l, r) -> (compileExpr l, compileExpr r) ||> sprintf "(%s * %s)"
| Divide (l, r) -> (compileExpr l, compileExpr r) ||> sprintf "(%s / %s)"
| Minus (l, r) -> (compileExpr l, compileExpr r) ||> sprintf "(%s - %s)"
| Int i -> string i
let rec evalExpr (e: Expr) =
match e with
| Parentheses e -> evalExpr e
| Plus (l, r) -> evalExpr l + evalExpr r
| Minus (l, r) -> evalExpr l - evalExpr r
| Divide (l, r) -> evalExpr l / evalExpr r
| Times (l, r) -> evalExpr l * evalExpr r
| Int i -> i