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 give True if the value is a Just and False if it is Nothing.

      isJust :: Maybe a -> Bool
    
  • fromMaybe starts with a “default value”, the answer to give when it gets Nothing. When it gets a Just, 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 the Just 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
    
Last modified November 19, 2024: Short review done in class. (15d0dab)