>>> maybe False odd (Just 3) True
>>> maybe False odd Nothing FalseRead an integer from a string using readMaybe. If we succeed, return twice the integer; that is, apply (*2) to it. If instead we fail to parse an integer, return 0 by default:
>>> import GHC.Internal.Text.Read ( readMaybe ) >>> maybe 0 (*2) (readMaybe "5") 10 >>> maybe 0 (*2) (readMaybe "") 0Apply show to a Maybe Int. If we have Just n, we want to show the underlying Int n. But if we have Nothing, we return the empty string instead of (for example) "Nothing":
>>> maybe "" show (Just 5) "5" >>> maybe "" show Nothing ""
>>> maybeAt 0 [] Nothing
>>> maybeAt 3 ["a", "b", "c"] Nothing
>>> maybeAt (-1) [1, 2, 3] Nothing
>>> maybeAt 2 ["a", "b", "c"] Just "c"
>>> maybeToList (Just 7) [7]
>>> maybeToList Nothing []One can use maybeToList to avoid pattern matching when combined with a function that (safely) works on lists:
>>> import GHC.Internal.Text.Read ( readMaybe ) >>> sum $ maybeToList (readMaybe "3") 3 >>> sum $ maybeToList (readMaybe "") 0
>>> :{ evenInHalf :: Int -> IO (Maybe Int) evenInHalf n | even n = pure $ Just $ n `div` 2 | otherwise = pure Nothing :}
>>> mapMaybeM evenInHalf [1..10] [1,2,3,4,5]
>>> catMaybes [Just 1, Nothing, Just 3] [1,3]When constructing a list of Maybe values, catMaybes can be used to return all of the "success" results (if the list is the result of a map, then mapMaybe would be more appropriate):
>>> import GHC.Internal.Text.Read ( readMaybe ) >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] [Just 1,Nothing,Just 3] >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ] [1,3]
>>> fromMaybe "" (Just "Hello, World!") "Hello, World!"
>>> fromMaybe "" Nothing ""Read an integer from a string using readMaybe. If we fail to parse an integer, we want to return 0 by default:
>>> import GHC.Internal.Text.Read ( readMaybe ) >>> fromMaybe 0 (readMaybe "5") 5 >>> fromMaybe 0 (readMaybe "") 0
>>> listToMaybe [] Nothing
>>> listToMaybe [9] Just 9
>>> listToMaybe [1,2,3] Just 1Composing maybeToList with listToMaybe should be the identity on singleton/empty lists:
>>> maybeToList $ listToMaybe [5] [5] >>> maybeToList $ listToMaybe [] []But not on lists with more than one element:
>>> maybeToList $ listToMaybe [1,2,3] [1]
>>> import GHC.Internal.Text.Read ( readMaybe ) >>> let readMaybeInt = readMaybe :: String -> Maybe Int >>> mapMaybe readMaybeInt ["1", "Foo", "3"] [1,3] >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"] [1,3]If we map the Just constructor, the entire list should be returned:
>>> mapMaybe Just [1,2,3] [1,2,3]
>>> readMaybe "123" :: Maybe Int Just 123
>>> readMaybe "hello" :: Maybe Int Nothing@since base-4.6.0.0