-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathset4a.hs
247 lines (216 loc) · 8.5 KB
/
set4a.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
-- Exercise set 4a:
--
-- * using type classes
-- * working with lists
--
-- Type classes you'll need
-- * Eq
-- * Ord
-- * Num
-- * Fractional
--
-- Useful functions:
-- * maximum
-- * minimum
-- * sort
module Set4a where
import Mooc.Todo
import Data.List
import Data.Ord
import qualified Data.Map as Map
import Data.Array
------------------------------------------------------------------------------
-- Ex 1: implement the function allEqual which returns True if all
-- values in the list are equal.
--
-- Examples:
-- allEqual [] ==> True
-- allEqual [1,2,3] ==> False
-- allEqual [1,1,1] ==> True
--
-- PS. check out the error message you get with your implementation if
-- you remove the Eq a => constraint from the type!
allEqual :: Eq a => [a] -> Bool
allEqual [] = True
allEqual list = if length (nub list) == 1 then True else False
------------------------------------------------------------------------------
-- Ex 2: implement the function distinct which returns True if all
-- values in a list are different.
--
-- Hint: a certain function from the lecture material can make this
-- really easy for you.
--
-- Examples:
-- distinct [] ==> True
-- distinct [1,1,2] ==> False
-- distinct [1,2] ==> True
distinct :: Eq a => [a] -> Bool
distinct [] = True
distinct [x] = True
distinct list = length (nub list) == (length list)
------------------------------------------------------------------------------
-- Ex 3: implement the function middle that returns the middle value
-- (not the smallest or the largest) out of its three arguments.
--
-- The function should work on all types in the Ord class. Give it a
-- suitable type signature.
--
-- Examples:
-- middle 'b' 'a' 'c' ==> 'b'
-- middle 1 7 3 ==> 3
middle:: (Ord a) => a->a->a->a
middle a b c = sort [a, b, c] !! 1
------------------------------------------------------------------------------
-- Ex 4: return the range of an input list, that is, the difference
-- between the smallest and the largest element.
--
-- Your function should work on all suitable types, like Float and
-- Int. You'll need to add _class constraints_ to the type of range.
--
-- It's fine if your function doesn't work for empty inputs.
--
-- Examples:
-- rangeOf [4,2,1,3] ==> 3
-- rangeOf [1.5,1.0,1.1,1.2] ==> 0.5
rangeOf :: (Ord a, Num a) => [a] -> a
rangeOf a = (sort a) !! ((length a)-1 ) - ((sort a) !! 0)
------------------------------------------------------------------------------
-- Ex 5: given a list of lists, return the longest list. If there
-- are multiple lists of the same length, return the list that has
-- the smallest _first element_.
--
-- (If multiple lists have the same length and same first element,
-- you can return any one of them.)
--
-- Give the longest function a suitable type.
--
-- Examples:
-- longest [[1,2,3],[4,5],[6]] ==> [1,2,3]
-- longest ["bcd","def","ab"] ==> "bcd"
longest [x] = x
longest a = longest' (take 2 (reverse (sortOn length a)))
longest' (a:b:[])
| (length a) > (length b) = a
| (length b) > (length a) = b
| otherwise = if max (a !! 0) (b !! 0) == (a !! 0) then b else a
------------------------------------------------------------------------------
-- Ex 6: Implement the function incrementKey, that takes a list of
-- (key,value) pairs, and adds 1 to all the values that have the given key.
--
-- You'll need to add _class constraints_ to the type of incrementKey
-- to make the function work!
--
-- The function needs to be generic and handle all compatible types,
-- see the examples.
--
-- Examples:
-- incrementKey True [(True,1),(False,3),(True,4)] ==> [(True,2),(False,3),(True,5)]
-- incrementKey 'a' [('a',3.4)] ==> [('a',4.4)]
incrementKey :: (Ord k, Num v) => k -> [(k,v)] -> [(k,v)]
incrementKey mainKey [] = []
incrementKey mainKey values = map (\(key, val)-> if key == mainKey then (key, val+1) else (key, val)) values
------------------------------------------------------------------------------
-- Ex 7: compute the average of a list of values of the Fractional
-- class.
--
-- There is no need to handle the empty list case.
--
-- Hint! since Fractional is a subclass of Num, you have all
-- arithmetic operations available
--
-- Hint! you can use the function fromIntegral to convert the list
-- length to a Fractional
average :: Fractional a => [a] -> a
average xs = sum xs / fromIntegral(length xs)
------------------------------------------------------------------------------
-- Ex 8: given a map from player name to score and two players, return
-- the name of the player with more points. If the players are tied,
-- return the name of the first player (that is, the name of the
-- player who comes first in the argument list, player1).
--
-- If a player doesn't exist in the map, you can assume they have 0 points.
--
-- Hint: Map.findWithDefault can make this simpler
--
-- Examples:
-- winner (Map.fromList [("Bob",3470),("Jane",2130),("Lisa",9448)]) "Jane" "Lisa"
-- ==> "Lisa"
-- winner (Map.fromList [("Mike",13607),("Bob",5899),("Lisa",5899)]) "Lisa" "Bob"
-- ==> "Lisa"
winner :: Map.Map String Int -> String -> String -> String
winner scores player1 player2
| getWinner player1 scores > getWinner player2 scores = player1
| getWinner player1 scores < getWinner player2 scores = player2
| otherwise = player1
getWinner :: String -> Map.Map String Int -> Int
getWinner key map = Map.findWithDefault 0 key map
------------------------------------------------------------------------------
-- Ex 9: compute how many times each value in the list occurs. Return
-- the frequencies as a Map from value to Int.
--
-- Challenge 1: try using Map.alter for this
--
-- Challenge 2: use foldr to process the list
--
-- Example:
-- freqs [False,False,False,True]
-- ==> Map.fromList [(False,3),(True,1)]
freqs :: (Eq a, Ord a) => [a] -> Map.Map a Int
freqs [] = Map.fromList []
freqs (x:xs) = Map.alter freqs' x (freqs xs)
freqs' :: Maybe Int ->Maybe Int
freqs' (Just x) = Just (x+1)
freqs' Nothing = Just (1)
------------------------------------------------------------------------------
-- Ex 10: recall the withdraw example from the course material. Write a
-- similar function, transfer, that transfers money from one account
-- to another.
--
-- However, the function should not perform the transfer if
-- * the from account doesn't exist,
-- * the to account doesn't exist,
-- * the sum is negative,
-- * or the from account doesn't have enough money.
--
-- Hint: there are many ways to implement this logic. Map.member or
-- Map.notMember might help.
--
-- Examples:
-- let bank = Map.fromList [("Bob",100),("Mike",50)]
-- transfer "Bob" "Mike" 20 bank
-- ==> fromList [("Bob",80),("Mike",70)]
-- transfer "Bob" "Mike" 120 bank
-- ==> fromList [("Bob",100),("Mike",50)]
-- transfer "Bob" "Lisa" 20 bank
-- ==> fromList [("Bob",100),("Mike",50)]
-- transfer "Lisa" "Mike" 20 bank
-- ==> fromList [("Bob",100),("Mike",50)]
transfer :: String -> String -> Int -> Map.Map String Int -> Map.Map String Int
transfer from to amount bank
| (allowTransfer from to amount bank) = Map.adjust (\x -> x + amount) to (Map.adjust (\x -> x - amount) from bank)
| otherwise = bank
allowTransfer :: String -> String -> Int -> Map.Map String Int -> Bool
allowTransfer from to amount bank = (Map.member from bank) && (Map.member to bank) && ((Map.findWithDefault 0 from bank) - amount >= 0) && (amount >= 0)
------------------------------------------------------------------------------
-- Ex 11: given an Array and two indices, swap the elements in the indices.
--
-- Example:
-- swap 2 3 (array (1,4) [(1,"one"),(2,"two"),(3,"three"),(4,"four")])
-- ==> array (1,4) [(1,"one"),(2,"three"),(3,"two"),(4,"four")]
swap :: Ix i => i -> i -> Array i a -> Array i a
swap i j arr = arr // [(i, (arr ! j)),(j, (arr ! i)) ]
------------------------------------------------------------------------------
-- Ex 12: given an Array, find the index of the largest element. You
-- can assume the Array isn't empty.
--
-- You may assume that the largest element is unique.
--
-- Hint: check out Data.Array.indices or Data.Array.assocs
maxIndex :: (Ix i, Ord a) => Array i a -> i
maxIndex arr = getMaxIndex' (assocs arr) (getMaxValue ((elems arr) !! 0 ) (assocs arr))
getMaxValue :: (Ix i, Ord a) => a -> [(i, a)] -> a
getMaxValue max [] = max
getMaxValue max ((i,x): xs) = if x > max then getMaxValue x xs else getMaxValue max xs
getMaxIndex' :: (Ix i, Ord a) => [(i, a)] -> a -> i
getMaxIndex' [(i,x)] _ = i
getMaxIndex' ((i, x): xs) max = if x == max then i else getMaxIndex' xs max