-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter_06_ex_4.fs
More file actions
105 lines (97 loc) · 3.69 KB
/
Chapter_06_ex_4.fs
File metadata and controls
105 lines (97 loc) · 3.69 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
module Chapter_06_ex_4
#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
type BinTree<'a,'b> =
| Leaf of 'a
| Node of BinTree<'a,'b> * 'b * BinTree<'a,'b>;;
// 6.4 1. leafValues
let leafValues tree =
let rec collectLeafValues tree collectedValues =
match tree with
| Leaf(leaf) -> leaf::collectedValues
| Node(leftTree,_, rightTree) -> (collectLeafValues leftTree collectedValues)
@ (collectLeafValues rightTree collectedValues)
collectLeafValues tree []
|> Set.ofList
// 6.4 2. nodeValues
let nodeValues tree =
let rec collectNodeValues tree collectedValues =
match tree with
| Leaf(_) -> collectedValues
| Node(left, value, right) -> value::(collectNodeValues left collectedValues)
@ (collectNodeValues right collectedValues)
collectNodeValues tree []
|> Set.ofList
// 6.4 3. values
let values tree =
let rec collectValues tree collectedLeafValues collectedNodeValues =
match tree with
| Leaf(leaf) -> (leaf::collectedLeafValues, collectedNodeValues)
| Node(left, value, right) ->
let leftValues = collectValues left collectedLeafValues collectedNodeValues
let rightValues = collectValues right collectedLeafValues collectedNodeValues
((fst leftValues)@(fst rightValues), value::(snd leftValues)@(snd(rightValues)))
let leafs, nodes = collectValues tree [] []
(leafs |> Set.ofList, nodes |> Set.ofList)
[<TestFixture>]
type ``Chapter 06 exercise 4 Tests``() =
[<Test>]
member x.``6.4 1. leafValues``() =
test <@
let tree = Node(
Node(
Leaf(1),
"a",
Node(
Leaf(2),
"b",
Leaf(3)
)
),
"c",
Leaf(3)
)
leafValues tree = Set[1;2;3]
@>
[<Test>]
member x.``6.4 2. nodeValues``() =
test <@
let tree = Node(
Node(
Leaf(1),
"a",
Node(
Leaf(2),
"b",
Leaf(3)
)
),
"b",
Leaf(3)
)
nodeValues tree = Set["a";"b"]
@>
[<Test>]
member x.``6.4 2. values``() =
test <@
let tree = Node(
Node(
Leaf(1),
"a",
Node(
Leaf(2),
"b",
Leaf(3)
)
),
"b",
Leaf(3)
)
values tree = (Set[1;2;3], Set["a";"b"])
@>