-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWeek01Intro02.hs
127 lines (81 loc) · 2.4 KB
/
Week01Intro02.hs
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Week01Intro02 where
-- Recap
--- 1. Data (with types)
--- 2. Functions, defined by Pattern Matching
-- Today: defining functions by recursion
--- Example 1: factorial
-- factorial 6 = 6 * 5 * 4 * 3 * 2 * 1
-- = 6 * factorial 5
factorial :: Integer -> Integer
factorial 0 = 1
factorial 1 = 1
factorial n = n * factorial (n-1)
-- factorial 6 = 6 * factorial (6-1)
-- = 6 * factorial 5
-- = 6 * (5 * factorial (5-1))
-- = ..
-- = 6 * (5 * (4 * (3 * (2 * factorial 1))))
-- = 6 * (5 * (4 * (3 * (2 * 1))))
-- = 720
--- Example 2: Recursive types
{-
data ListofCards
= NoCards
| OneCard Card
| TwoCards Card Card
| ThreeCards Card Card Card
-}
data ListOfInts
= NoInts
| ConsInt Int ListOfInts
deriving Show
---- Sum of a list of integers
sumListOfInts :: ListOfInts -> Int
sumListOfInts NoInts = 0
sumListOfInts (ConsInt x xs) = x + sumListOfInts xs
-- sumListOfInts (ConsInt 12 (ConsInt 76 NoInts))
-- = 12 + sumListOfInts (ConsInt 76 NoInts)
-- = 12 + (76 + sumListOfInts NoInts)
-- = 12 + (76 + 0)
-- = 88
---- List a
data List a
= Nil
| Cons a (List a) --- Int ListOfInts
deriving Show
-- abstraction:
-- double x = 2 * x
---
-- multiply n x = n * x
---- Sum of a list of integers
sumList :: List Int -> Int
sumList Nil = 0
sumList (Cons x xs) = x + sumList xs
---- Product of a list of integers
productList :: List Int -> Int
productList Nil = 1
productList (Cons x xs) = x * productList xs
---- Making Lists
range :: Int -> List Int
range 0 = Nil
range n = if n < 0 then Cons n (range (n+1)) else Cons n (range (n-1))
-- range 5 = Cons 5 (Cons 4 (Cons 3 (Cons 2 (Cons 1 Nil))))
---- Factorial by combing product and 'range'
factorial_v2 :: Int -> Int
factorial_v2 n = result
where numbersFromN = range n
result = productList numbersFromN
---- Actual lists
-- data [a]
-- = [] -- Nil
-- | a : [a] -- Cons a (List a)
---- Search and replace in strings
-- type String = [Char]
-- A function to capitalise all 'e's in a String:
capitaliseEs :: String -> String
-- [Char] -> [Char]
capitaliseEs "" = ""
capitaliseEs (c:cs) = if c == 'e' then 'E' : capitaliseEs cs else c : capitaliseEs cs
-- capitaliseEs ('e':cs) = 'E' : capitaliseEs cs
-- capitaliseEs (c:cs) = c : capitaliseEs cs