@@ -9,7 +9,10 @@ type color =
99 Teisendab värvi sõneks, vastavalt "R", "G" ja "B".
1010 Kasutada match-i. *)
1111let show_color (c : color ): string =
12- failwith " TODO"
12+ match c with
13+ | Red -> " R"
14+ | Green -> " G"
15+ | Blue -> " B"
1316
1417(* * Ülesanne:
1518 Teisendab sõne värviks. show_color pöördfunktsioon.
@@ -22,6 +25,10 @@ let parse_color (s: string): color =
2225
2326(* * Algebralised andmetüübid. *)
2427
28+ (* type inttree =
29+ | Leaf of int
30+ | Branch of inttree * inttree *)
31+
2532(* * Polümorfne kahendpuu, mille elemendid on tüüpi 'a. *)
2633type 'a tree =
2734 | Leaf of 'a (* * Leht sisaldab ühte väärtust. *)
@@ -37,32 +44,61 @@ type 'a tree =
3744 . 4
3845 / \
3946 2 3 *)
40- let example_int_tree = Leaf 1
47+ let example_int_tree =
48+ Branch (
49+ Leaf 1 ,
50+ Branch (
51+ Branch (
52+ Branch (
53+ Leaf 2 ,
54+ Leaf 3
55+ ),
56+ Leaf 4
57+ ),
58+ Leaf 5
59+ )
60+ )
4161
4262(* * Ülesanne:
4363 .
4464 / \
4565 . .
4666 / \ / \
4767 'a' 'b' 'b' 'a' *)
48- let example_char_tree = Leaf 'a'
68+ let example_char_tree =
69+ Branch (
70+ Branch (
71+ Leaf 'a' ,
72+ Leaf 'b'
73+ ),
74+ Branch (
75+ Leaf 'b' ,
76+ Leaf 'a'
77+ )
78+ )
4979
5080
5181(* * Näited. *)
5282
5383(* * Arvutab puu kõrguse. Lehe kõrgus on 0.
5484 Vihje: Kasuta max funktsiooni. *)
5585let rec height (t : 'a tree ): int =
56- failwith " TODO"
86+ match t with
87+ | Leaf _ -> 0
88+ | Branch (l , r ) -> 1 + max (height l) (height r)
5789
5890(* * Teisendab puu sõneks. Vt teste.
5991 Vihje: Sõnede konkateneerimise operaator on ^. *)
6092let rec show_tree (show_leaf : 'a -> string ) (t : 'a tree ): string =
61- failwith " TODO"
93+ match t with
94+ | Leaf x -> show_leaf x
95+ | Branch (l , r ) -> " (" ^ show_tree show_leaf l ^ " " ^ show_tree show_leaf r ^ " )"
6296
6397(* * Rakendab funktsooni puu lehtedele. *)
6498let rec tree_map (f : 'a -> 'b ) (t : 'a tree ): 'b tree =
65- failwith " TODO"
99+ match t with
100+ | Leaf x -> Leaf (f x)
101+ | Branch (l , r ) -> Branch (tree_map f l, tree_map f r)
66102
67103
68104(* * Ülesanded. *)
0 commit comments