-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdt.hs
More file actions
55 lines (45 loc) · 2.24 KB
/
Adt.hs
File metadata and controls
55 lines (45 loc) · 2.24 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
data IntList = Empty -- equivalent to []
| Cons Int IntList -- equivalent to (:)
deriving Show
-- [] and : are also labels (and functions) just like any constructor.
list0 :: IntList
list0 = Empty
list1 :: IntList
list1 = Cons 1 list0 -- Cons 1 Empty
list2 :: IntList
list2 = Cons 2 list1 -- Cons 2 (Cons 1 Empty)
lengthIntList :: IntList -> Int
lengthIntList Empty = 0
lengthIntList (Cons x xs) = 1 + lengthIntList xs
-- Exercise: define a function to product all the elements of an IntList
prodIntList :: IntList -> Int
prodIntList Empty = 1
prodIntList (Cons x y) = x * prodIntList y
data Tree = Leaf
| Node Tree Int Tree
deriving Show
dummyTree :: Tree
dummyTree = Node (Node Leaf 2 Leaf) 50 (Node Leaf 3 (Node Leaf 42 Leaf))
dummyTree2 = Node (Node Leaf 3 Leaf) 1 (Node Leaf 1 (Node Leaf 2 Leaf))
existsInTree :: Int -> Tree -> Bool
existsInTree x Leaf = False
existsInTree x (Node left y right) = x == y || existsInTree x left || existsInTree x right
-- EXERCISE: Find the largest number in a tree with only positive integers (1,2,...)
-- If the tree is a leaf, return 0.
largestInTree :: Tree -> Int
largestInTree Leaf = 0
--largestInTree (Node left x right)
-- | (x >= largestInTree left) && (x >= largestInTree right) = x
-- | largestInTree left >= largestInTree right = largestInTree left
-- | largestInTree right > largestInTree left = largestInTree right
-- | otherwise = error "Unexpected case"
--largestInTree (Node left x right)
-- | maximum [x, (largestInTree left), largestInTree(right)] == x = x
-- | maximum [x, (largestInTree left), largestInTree(right)] == largestInTree left = largestInTree left
-- | maximum [x, (largestInTree left), largestInTree(right)] == largestInTree right = largestInTree right
-- | otherwise = error "Unexpected case"
largestInTree (Node left x right) = maximum [x, (largestInTree left), largestInTree(right)]
-- EXERCISE: multiply all numbers in a tree
prodTree :: Tree -> Int
prodTree Leaf = 1
prodTree (Node left x right) = x * prodTree left * prodTree right