-
Notifications
You must be signed in to change notification settings - Fork 5
/
live11.fsx
80 lines (61 loc) · 2.51 KB
/
live11.fsx
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
module BinaryTree =
// Data type
type Tree<'lab> =
| Leaf of 'lab
| Branch of Tree<'lab> * Tree<'lab>
// Computing the list of leaves
(*
Version without explicit type annotations, which works:
let rec leaves tree =
match tree with
| Leaf lab -> [lab]
| Branch (left, right) -> leaves left @ leaves right
*)
let rec leaves<'lab> (tree : Tree<'lab>) : list<'lab> =
match tree with
| Leaf lab -> [lab]
| Branch (left, right) -> leaves<'lab> left @ leaves<'lab> right
// annotation not needed in the last line
// Transforming labels
let rec map<'srcLab, 'dstLab> (f : 'srcLab -> 'dstLab)
(tree : Tree<'srcLab>)
: Tree<'dstLab> =
match tree with
| Leaf lab -> Leaf (f lab)
| Branch (left, right) -> Branch (map f left, map f right)
module PerfectBinaryTree =
// Data type
type Tree<'lab> =
| Simple of 'lab
| Complex of Tree<'lab * 'lab>
// Example trees
let example1 = Simple 1
let example2 = Complex (Simple (1, 2))
let example3 = Complex (Complex (Simple ((1, 2), (3, 4))))
let example4 = Complex (Complex (Complex (Simple (((1, 2), (3, 4)),
((5, 6), (7, 8))))))
// Computing the list of leaves
(*
Version without explicit type annotations, which does not work:
let rec leaves tree =
match tree with
| Simple lab -> [lab]
| Complex tree' -> let pairToList (lab1, lab2) = [lab1; lab2]
leaves tree' |> List.collect pairToList
*)
let rec leaves<'lab> (tree : Tree<'lab>) : list<'lab> =
match tree with
| Simple lab -> [lab]
| Complex tree' -> let pairToList (lab1, lab2) = [lab1; lab2]
leaves<'lab * 'lab> tree' |> List.collect pairToList
// annotation not needed in the last line
// Transforming labels
let rec map<'srcLab, 'dstLab> (f : 'srcLab -> 'dstLab)
(tree : Tree<'srcLab>)
: Tree<'dstLab> =
match tree with
| Simple lab
-> Simple (f lab)
| Complex tree'
-> let f' (lab1, lab2) = f lab1, f lab2
Complex (map<'srcLab * 'srcLab, 'dstLab * 'dstLab> f' tree')