Course map
Haskell // 17

Maybe and Either

Read

Maybe

A value that might be missing has type Maybe a: either Just x or Nothing. The compiler makes you handle both cases, so there is no null pointer surprise.

safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv a b = Just (a `div` b)

describe :: Maybe Int -> String
describe Nothing  = "no result"
describe (Just n) = "result: " ++ show n

main :: IO ()
main = do
  putStrLn (describe (safeDiv 10 2))   -- result: 5
  putStrLn (describe (safeDiv 1 0))    -- no result
  print (lookup "b" [("a", 1), ("b", 2)])  -- Just 2

lookup finds a key in a list of pairs and returns Maybe. The helper maybe fallback f m handles both cases in one expression: maybe 0 (+ 1) (Just 5) is 6.

01 / 05