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
|
module Maybe
( Maybe (..)
, maybe
, isJust, isNothing
, fromJust, fromMaybe
, listToMaybe, maybeToList
, catMaybes, mapMaybe
, (>>-), sequenceMaybe, mapMMaybe, mplus
) where
infixl 1 >>-
isJust :: Maybe _ -> Bool
isJust (Just _) = True
isJust Nothing = False
isNothing :: Maybe _ -> Bool
isNothing Nothing = True
isNothing (Just _) = False
fromJust :: Maybe a -> a
fromJust (Just a) = a
fromJust Nothing = error "Maybe.fromJust: Nothing"
fromMaybe :: a -> Maybe a -> a
fromMaybe d Nothing = d
fromMaybe _ (Just a) = a
listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe (a : _) = Just a
maybeToList :: Maybe a -> [a]
maybeToList Nothing = []
maybeToList (Just a) = [a]
catMaybes :: [Maybe a] -> [a]
catMaybes ms = [ m | (Just m) <- ms ]
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe f = catMaybes . map f
(>>-) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>- _ = Nothing
Just x >>- f = f x
sequenceMaybe :: [Maybe a] -> Maybe [a]
sequenceMaybe [] = Just []
sequenceMaybe (c:cs) = c >>- \x -> sequenceMaybe cs >>- \xs -> Just (x:xs)
mapMMaybe :: (a -> Maybe b) -> [a] -> Maybe [b]
mapMMaybe f = sequenceMaybe . map f
mplus :: Maybe a -> Maybe a -> Maybe a
Nothing `mplus` y = y
x@(Just _) `mplus` _ = x
|