Advertisement
Guest User

Untitled

a guest
Apr 20th, 2014
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.33 KB | None | 0 0
  1. (*  Artem Lobanov (c) 2014
  2.     Arithmetic expression simplifier
  3. *)
  4.  
  5. type Expr =
  6.     | Const of int
  7.     | Var of string
  8.     | Add of Expr * Expr
  9.     | Sub of Expr * Expr
  10.     | Mul of Expr * Expr
  11.     | Div of Expr * Expr
  12.  
  13. let rec calc expr =
  14.     let calcable operand1 operand2 exprFunc arithmFunc =
  15.         match (calc operand1, calc operand2) with
  16.         | (Const aResult, Const bResult) -> Const (arithmFunc aResult bResult)
  17.         | _ -> exprFunc (calc operand1, calc operand2)
  18.  
  19.     match expr with
  20.     | Const a -> Const a
  21.     | Var x -> Var x
  22.     | Add (a, b) -> match (calc a, calc b) with
  23.                         | (Const 0, Var bResult) -> Var bResult
  24.                         | (Var aResult, Const 0) -> Var aResult
  25.                         | _ -> calcable a b Add (+)
  26.     | Sub (a, b) -> match (calc a, calc b) with
  27.                         | (Var aResult, Var bResult) -> Const 0
  28.                         | _ -> calcable a b Add (-)
  29.     | Mul (a, b) -> match (calc a, calc b) with
  30.                         | (Const 0, Var result) | (Var result, Const 0) -> Const 0
  31.                         | _ -> calcable a b Add (*)
  32.     | Div (a, b) -> match (calc a, calc b) with
  33.                         | (Var aResult, Const 1) -> Var aResult
  34.                         | _ -> calcable a b Add (/)
  35.  
  36. printfn "%A" (calc(Sub(Const 0, Var "x")))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement