-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathex2.hs
63 lines (52 loc) · 1.18 KB
/
ex2.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
-- a. all
all :: (a -> Bool) -> [a] -> Bool
all p = and . map p
all' :: (a -> Bool) -> [a] -> Bool
all' p = foldr (\x y -> p x && y) True
all'' :: (a -> Bool) -> [a] -> Bool
all'' p [] = True
all'' p (x:xs) = p x && all'' p xs
-- b. any
any :: (a -> Bool) -> [a] -> Bool
any p = or . map p
any' :: (a -> Bool) -> [a] -> Bool
any' p = foldr (\x y -> p x || y) False
any'' :: (a -> Bool) -> [a] -> Bool
any'' p [] = False
any'' p (x:xs) = p x || any'' p xs
-- c. takeWhile
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p =
foldr
(\x xs ->
if p x
then x : xs
else [])
[]
takeWhile'' :: (a -> Bool) -> [a] -> [a]
takeWhile'' p [] = []
takeWhile'' p (x:xs)
| p x = x : takeWhile'' p xs
| otherwise = []
takeWhile''' :: (a -> Bool) -> [a] -> [a]
takeWhile''' p =
foldl
(\xs x ->
if p x
then xs ++ [x]
else xs)
[]
-- d. dropWhile
dropWhile' :: (a -> Bool) -> [a] -> [a]
dropWhile' p =
foldl
(\xs x ->
if (p x) && (length xs == 0)
then []
else xs ++ [x])
[]
dropWhile'' :: (a -> Bool) -> [a] -> [a]
dropWhile'' p [] = []
dropWhile'' p (x:xs)
| p x = dropWhile'' p xs
| otherwise = x : xs