on master help sign in
Add more examples
57c4b79Evan Czaplicki
libraries/Maybe.elm+21−3
@@ -21,27 +21,45 @@ numbers).
21-}
21-}
22data Maybe a = Just a | Nothing
22data Maybe a = Just a | Nothing
23
23
24−{-| Apply a function to the contents of a `Maybe`.
24+{-| Provide a default value and a function to extract the contents of a `Maybe`.
25−Return default when given `Nothing`.
25+When given `Nothing` you get the default, when given a `Just` you apply the
26+function to the associated value.
27+
28+ isPositive : Maybe Int -> Bool
29+ isPositive maybeInt = maybe False (\n -> n > 0) maybeInt
30+
31+ map : (a -> b) -> Maybe a -> Maybe b
32+ map f m = maybe Nothing (\x -> Just (f x)) m
26-}
33-}
27maybe : b -> (a -> b) -> Maybe a -> b
34maybe : b -> (a -> b) -> Maybe a -> b
28maybe b f m = case m of
35maybe b f m = case m of
29 Just v -> f v
36 Just v -> f v
30 Nothing -> b
37 Nothing -> b
31
38
32−{-| Check if constructed with `Just`.
39+{-| Check if a maybe happens to be a `Just`.
40+
41+ isJust (Just 42) == True
42+ isJust (Just []) == True
43+ isJust Nothing == False
33-}
44-}
34isJust : Maybe a -> Bool
45isJust : Maybe a -> Bool
35isJust = maybe False (\_ -> True)
46isJust = maybe False (\_ -> True)
36
47
37{-| Check if constructed with `Nothing`.
48{-| Check if constructed with `Nothing`.
49+
50+ isNothing (Just 42) == False
51+ isNothing (Just []) == False
52+ isNothing Nothing == True
38-}
53-}
39isNothing : Maybe a -> Bool
54isNothing : Maybe a -> Bool
40isNothing = not . isJust
55isNothing = not . isJust
41
56
57+cons : Maybe a -> [a] -> [a]
42cons mx xs = maybe xs (\x -> x :: xs) mx
58cons mx xs = maybe xs (\x -> x :: xs) mx
43
59
44{-| Filters out Nothings and extracts the remaining values.
60{-| Filters out Nothings and extracts the remaining values.
61+
62+ justs [Just 0, Nothing, Just 5, Just 7] == [0,5,7]
45-}
63-}
46justs : [Maybe a] -> [a]
64justs : [Maybe a] -> [a]
47justs = foldr cons []
65justs = foldr cons []