7. Review Maybe
A few Data.Maybe helper functions: fromJust, isJust, mapMaybe.
There are a bunch of helper functions in
Data.Maybe
. My
favorite is mapMaybe
. Choose pattern matching over these functions
when you can.
-
isJust
should giveTrue
if the value is aJust
andFalse
if it isNothing
.isJust :: Maybe a -> Bool
-
fromMaybe
starts with a “default value”, the answer to give when it getsNothing
. When it gets aJust
, it gives the value inside.fromMaybe :: Int -> Maybe Int -> Int check_fM = [ 109 == fromMaybe 109 Nothing, 280 == fromMaybe 109 (Just 280) ]
-
mapMaybe
runs a function on all of the elements in a list and keeps only theJust
results.mapMaybe :: (a -> Maybe b) -> [a] -> [b] check_mM = ([11,13] == mapMaybe f [1..4]) where f n | odd n = Just (n+10) | even n = Nothing