on master help sign in
Add Maybe.map
218f2f4Evan Czaplicki
libraries/Maybe.elm+14−4
@@ -1,4 +1,4 @@
1−module Maybe (Maybe(..), maybe, isJust, isNothing) where
1+module Maybe (Maybe(..), maybe, isJust, isNothing, map) where
2
2
3{-| Represents an optional value. Maybe it is there, maybe it is not.
3{-| Represents an optional value. Maybe it is there, maybe it is not.
4
4
@@ -8,6 +8,8 @@ module Maybe (Maybe(..), maybe, isJust, isNothing) where
8# Taking Maybes apart
8# Taking Maybes apart
9@docs maybe, isJust, isNothing
9@docs maybe, isJust, isNothing
10
10
11+# Map
12+@docs map
11-}
13-}
12
14
13import Basics (not, (.))
15import Basics (not, (.))
@@ -24,9 +26,6 @@ function to the associated value.
24
26
25 isPositive : Maybe Int -> Bool
27 isPositive : Maybe Int -> Bool
26 isPositive maybeInt = maybe False (\n -> n > 0) maybeInt
28 isPositive maybeInt = maybe False (\n -> n > 0) maybeInt
27−
28− map : (a -> b) -> Maybe a -> Maybe b
29− map f m = maybe Nothing (\x -> Just (f x)) m
30-}
29-}
31maybe : b -> (a -> b) -> Maybe a -> b
30maybe : b -> (a -> b) -> Maybe a -> b
32maybe b f m =
31maybe b f m =
@@ -51,3 +50,14 @@ isJust = maybe False (\_ -> True)
51-}
50-}
52isNothing : Maybe a -> Bool
51isNothing : Maybe a -> Bool
53isNothing = not . isJust
52isNothing = not . isJust
53+
54+{-| Transform the contents of a `Maybe` with a given function:
55+
56+ map sqrt (Just 9) == Just 3
57+ map sqrt Nothing == Nothing
58+-}
59+map : (a -> b) -> Maybe a -> Maybe b
60+map f maybe =
61+ case maybe of
62+ Just v -> Just (f v)
63+ Nothing -> Nothing