-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChapter4.hs
165 lines (107 loc) · 2.04 KB
/
Chapter4.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
module Chapter4 where
import Prelude hiding ((&&))
{-
WAVE!!!! :D
Defining Functions
-}
isDigit' :: Char -> Bool
isDigit' c = (c >= '0') && (c <= '9')
even' :: Integral a => a -> Bool
even' x = x `mod` 2 == 0
splitAt' :: Int -> [a] -> ([a], [a])
splitAt' n xs = (take n xs, drop n xs)
{-
Conditional Expressions
-}
abs' :: Int -> Int
abs' x = if x >= 0 then x else (-x)
signum' :: Int -> Int
signum' n = if n < 0
then (-1)
else if n == 0
then 0
else 1
{-
Guarded Equations
-}
abs'' :: Int -> Int
abs'' n | n == 0 = 0
| n > 0 = n
| otherwise = (-n)
signum'' :: Int -> Int
signum'' n | n < 0 = (-1)
| n == 0 = 0
| n > 0 = 1
{-
Pattern Matching
-}
not' :: Bool -> Bool
not' True = False
not' False = True
(&&) :: Bool -> Bool -> Bool
True && True = True
True && False = False
False && True = False
False && False = False
--or
ands :: Bool -> Bool -> Bool
True `ands` True = True
_ `ands` _ = False
--or
ands2 :: Bool -> Bool -> Bool
True `ands2` x = x
False `ands2` _ = False
{-
Tuple Patterns
-}
fst' :: (a, b) -> a
fst' (x, _) = x
snd' :: (a, b) -> b
snd' (_, x) = x
{-
List Patterns
-}
test :: [Char] -> Bool
test ['a', _, _] = True
test _ = False
{-
matching on cons
[1, 2, 3]
1 : [2, 3]
1 : 2 : [3]
1 : 2 : 3 : []
-}
test' :: [Char] -> Bool
test' ('a' : _) = True
test' _ = False
null' :: [a] -> Bool
null' [] = True
null' (_ : _) = False
head' :: [a] -> a
head' (x : _) = x
head' [] = error "empty"
tail' :: [a] -> [a]
tail' [] = error "empty"
tail' (_ : xs) = xs
{-
Lambda Expressions
Anonymous Functions
"functions with no name"
-}
double :: Int -> Int
double = \ x -> x + x
{-
var double = function(x) {
return x + x;
};
-}
add :: Int -> Int -> Int
add x y = x + y
add' :: Int -> Int -> Int
add' y = \ x -> x + y
add'' :: Int -> Int -> Int
add'' = \ x -> \ y -> x + y
{-
Sections
same as currying but you could curry on both args on a infix op
-}