@@ -1,12 +1,71 @@
11module prelude.maybe
22
3−data Maybe a = Nothing | Just a
3+import builtins
4+import prelude.list
5+import prelude.monad
6+
7+data Maybe a
8+ = Nothing
9+ | Just a
10+
11+--------------------------------------------------------------------------------
12+-- Syntactic tests
13+--------------------------------------------------------------------------------
14+
15+isNothing : Maybe a -> Bool
16+isNothing Nothing = True
17+isNothing (Just j) = False
18+
19+isJust : Maybe a -> Bool
20+isJust Nothing = False
21+isJust (Just j) = True
22+
23+--------------------------------------------------------------------------------
24+-- Conversions
25+--------------------------------------------------------------------------------
26+
27+maybeToList : Maybe a -> List a
28+maybeToList Nothing = []
29+maybeToList (Just j) = [j]
30+
31+listToMaybe : List a -> Maybe a
32+listToMaybe [] = Nothing
33+listToMaybe (x::xs) = Just x
34+
35+--------------------------------------------------------------------------------
36+-- Misc
37+--------------------------------------------------------------------------------
438
539maybe : |(def : b) -> (a -> b) -> Maybe a -> b
640maybe n j Nothing = n
741maybe n j (Just x) = j x
842
43+fromMaybe : |(def: a) -> Maybe a -> a
44+fromMaybe def Nothing = def
45+fromMaybe def (Just j) = j
46+
47+toMaybe : Bool -> a -> Maybe a
48+toMaybe True j = Just j
49+toMaybe False j = Nothing
50+
51+catMaybes : List (Maybe a) -> List a
52+catMaybes [] = []
53+catMaybes (x::xs) =
54+ case x of
55+ Nothing => catMaybes xs
56+ Just j => j :: catMaybes xs
57+
58+mapMaybe : (a -> Maybe b) -> List a -> List b
59+mapMaybe f [] = []
60+mapMaybe f (x::xs) =
61+ case f x of
62+ Nothing => mapMaybe f xs
63+ Just j => j :: mapMaybe f xs
64+
65+--------------------------------------------------------------------------------
66+-- Class instances
67+--------------------------------------------------------------------------------
68+
969maybe_bind : Maybe a -> (a -> Maybe b) -> Maybe b
10−maybe_bind Nothing k = Nothing
70+maybe_bind Nothing k = Nothing
1171maybe_bind (Just x) k = k x
12−