From 57c4b79eb34e9b9a6dde9ca621a996ec0a458ae3 Mon Sep 17 00:00:00 2001 From: Evan Czaplicki Date: Tue, 18 Feb 2014 18:06:14 -0500 Subject: [PATCH] Add more examples Based on very valid observation here (https://groups.google.com/forum/#!topic/elm-discuss/_vvE0OWNKDU) that these docs were bad before. --- libraries/Maybe.elm | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/libraries/Maybe.elm b/libraries/Maybe.elm index c633467..8769cf8 100644 --- a/libraries/Maybe.elm +++ b/libraries/Maybe.elm @@ -21,27 +21,45 @@ numbers). -} data Maybe a = Just a | Nothing -{-| Apply a function to the contents of a `Maybe`. -Return default when given `Nothing`. +{-| Provide a default value and a function to extract the contents of a `Maybe`. +When given `Nothing` you get the default, when given a `Just` you apply the +function to the associated value. + + isPositive : Maybe Int -> Bool + isPositive maybeInt = maybe False (\n -> n > 0) maybeInt + + map : (a -> b) -> Maybe a -> Maybe b + map f m = maybe Nothing (\x -> Just (f x)) m -} maybe : b -> (a -> b) -> Maybe a -> b maybe b f m = case m of Just v -> f v Nothing -> b -{-| Check if constructed with `Just`. +{-| Check if a maybe happens to be a `Just`. + + isJust (Just 42) == True + isJust (Just []) == True + isJust Nothing == False -} isJust : Maybe a -> Bool isJust = maybe False (\_ -> True) {-| Check if constructed with `Nothing`. + + isNothing (Just 42) == False + isNothing (Just []) == False + isNothing Nothing == True -} isNothing : Maybe a -> Bool isNothing = not . isJust +cons : Maybe a -> [a] -> [a] cons mx xs = maybe xs (\x -> x :: xs) mx {-| Filters out Nothings and extracts the remaining values. + + justs [Just 0, Nothing, Just 5, Just 7] == [0,5,7] -} justs : [Maybe a] -> [a] justs = foldr cons []