-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch06_solutions.hs
64 lines (52 loc) · 1.19 KB
/
ch06_solutions.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
module ProgrammingInHaskell_Ch06 where
import Prelude hiding (and, concat, elem, last, replicate, sum, take, (!!))
-- Q6a
and :: [Bool] -> Bool
and [] = True
and (x:xs) = x && and xs
-- Q6b
concat :: [[a]] -> [a]
concat [] = []
concat (xs:xss) = xs ++ concat xss
-- Q6c
replicate :: Int -> a -> [a]
replicate 0 _ = []
replicate n x = x : replicate (n-1) x
-- Q6d
(!!) :: [a] -> Int -> a
(!!) (x:xs) 1 = x
(!!) (x:xs) n = (!!) xs (n-1)
-- Q6e
elem :: Eq a => a -> [a] -> Bool
elem e [] = False
elem e (x:xs)
| e == x = True
| otherwise = elem e xs
-- Q7
merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
| x < y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
-- Q8
halve :: [a] -> ([a],[a])
halve xs = ((take n xs), (drop n xs))
where n = length xs `div` 2
msort :: Ord a => [a] -> [a]
msort [] = []
msort [x] = [x]
msort xs = merge (msort ys) (msort zs)
where (ys,zs) = halve xs
-- Q9a
sum :: Num a => [a] -> a
sum [] = 0
sum (x:xs) = x + sum xs
-- Q9b
take :: Int -> [a] -> [a]
take 0 xs = []
take n (x:xs) = x : take (n-1) xs
-- Q9c
last :: [a] -> a
last (x:[]) = x
last (x:xs) = last xs