-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpression.fs
More file actions
76 lines (61 loc) · 1.52 KB
/
Expression.fs
File metadata and controls
76 lines (61 loc) · 1.52 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
namespace ConsoleCalc
open System
type Constant = PI | E
type Unary = Plus | Minus
type Binary =
| Add | Sub
| Mul | Div
| Mod | Pow
type Function =
| Sin | Cos | Tan
| Log10 | Log | Abs
| Sign | Sqrt | Round
type Expression =
| Number of float
| Constant of Constant
| Unary of Unary * Expression
| Binary of Binary * Expression * Expression
| Function of Function * Expression
[<RequireQualifiedAccess>]
module Constant =
let toFloat = function
| PI -> Math.PI
| E -> Math.E
[<RequireQualifiedAccess>]
module Unary =
let toFunc : Unary -> float -> float = function
| Plus -> fun i -> i
| Minus -> fun i -> -i
[<RequireQualifiedAccess>]
module Binary =
let toFunc = function
| Add -> (+)
| Sub -> (-)
| Mul -> (*)
| Div -> (/)
| Pow -> ( ** )
| Mod -> (%)
[<RequireQualifiedAccess>]
module Function =
let toFunc = function
| Sin -> Math.Sin
| Cos -> Math.Cos
| Tan -> Math.Tan
| Log10 -> Math.Log10
| Log -> Math.Log
| Abs -> Math.Abs
| Sign -> Math.Sign >> float
| Sqrt -> Math.Sqrt
| Round -> Math.Round
[<RequireQualifiedAccess>]
module Expression =
let fromFloat = Number
let fromConstant = Constant
let fromUnary u e = Unary (u, e)
let fromBinary b e1 e2 = Binary (b, e1, e2)
let rec solve = function
| Number f -> f
| Constant c -> Constant.toFloat c
| Unary (u, e) -> Unary.toFunc u (solve e)
| Binary (b, e1, e2) -> Binary.toFunc b (solve e1) (solve e2)
| Function (f, e) -> Function.toFunc f (solve e)