-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExMaybe.hs
70 lines (56 loc) · 1.31 KB
/
ExMaybe.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
module ExMaybe where
-- Do not alter this import!
import Prelude hiding ( maybe, Maybe(..) )
import qualified Data.Maybe as M
data Maybe a = Nothing | Just a
deriving (Show, Eq, Ord)
catMaybes :: [Maybe a] -> [a]
catMaybes [] = []
catMaybes (x:xs) =
case x of
Nothing -> catMaybes xs
Just thing -> thing : catMaybes xs
myLookup :: Eq a => a -> [(a,b)] -> Maybe b
myLookup _ [] = Nothing
myLookup x ((y,z):ys)
|x == y = Just z
|otherwise = myLookup x ys
fromJust :: Maybe a -> a
fromJust x =
case x of
Nothing -> error "Nothing"
Just thing -> thing
fromMaybe :: a -> Maybe a -> a
fromMaybe x y =
case y of
Just thing -> thing
Nothing -> x
isJust :: Maybe a -> Bool
isJust x =
case x of
Just thing -> True
otherwise -> False
isNothing :: Maybe a -> Bool
isNothing x =
case x of
Nothing -> True
otherwise -> False
listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe (x:xs) = Just x
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe _ [] = []
mapMaybe f (x:xs) =
case f x of
Nothing -> mapMaybe f xs
otherwise -> fromJust (f x) : mapMaybe f xs
maybe :: b -> (a -> b) -> Maybe a -> b
maybe x f m =
case m of
Nothing -> x
ohterwise -> f (fromJust m)
maybeToList :: Maybe a -> [a]
maybeToList x =
case x of
Nothing -> []
otherwise -> [fromJust x]