-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter_06_ex_2.fs
More file actions
51 lines (48 loc) · 1.91 KB
/
Chapter_06_ex_2.fs
File metadata and controls
51 lines (48 loc) · 1.91 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
module Chapter_06_ex_2
#if INTERACTIVE
#r "packages/Unquote.2.2.2/lib/net40/unquote.dll"
#r "packages/NUnit.2.6.2/lib/nunit.framework.dll"
#endif
open System
open System.Globalization
open NUnit.Framework
open Swensen.Unquote
// 6.2 post fix form
type Fexpr = | Const of float
| X // What is this doing??
| Add of Fexpr * Fexpr
| Sub of Fexpr * Fexpr
| Mul of Fexpr * Fexpr
| Div of Fexpr * Fexpr
| Sin of Fexpr
| Cos of Fexpr
| Log of Fexpr
| Exp of Fexpr
let rec toPostFix expression =
match expression with
| Const(value) -> String.Format(CultureInfo.InvariantCulture, "{0:0.0######}", value)
| Add(left, right) -> toPostFix(left) + " " + toPostFix(right) + " +"
| Sub(left, right) -> toPostFix(left) + " " + toPostFix(right) + " -"
| Mul(left, right) -> toPostFix(left) + " " + toPostFix(right) + " *"
| Div(left, right) -> toPostFix(left) + " " + toPostFix(right) + " /"
| Sin(expr) -> toPostFix(expr) + " sin"
| Cos(expr) -> toPostFix(expr) + " cos"
| Log(expr) -> toPostFix(expr) + " log"
| Exp(expr) -> toPostFix(expr) + " exp"
| expr -> toPostFix(expr)
[<TestFixture>]
type ``Chapter 06 exercise 2 Tests``() =
[<Test>]
member x.``6.2 format expressions in postfix form``() =
test <@ toPostFix(Add(Const(7.0), Const(14.0))) = "7.0 14.0 +" @>
test <@ toPostFix(Mul(
Add(Const(7.0), Const(14.0)),
Sub(Const(6.0), Const(12.0))))
= "7.0 14.0 + 6.0 12.0 - *"
@>
test <@ toPostFix(Sin(
Mul(
Add(Const(7.0), Const(14.0)),
Sub(Const(6.0), Const(12.0)))))
= "7.0 14.0 + 6.0 12.0 - * sin"
@>