Code
haskell
-- Maybe: handle nullability
safeDiv :: Double -> Double -> Maybe Double
safeDiv _ 0 = Nothing
safeDiv x y = Just (x / y)
-- Chain Maybes with >>= (bind)
compute :: Double -> Double -> Double -> Maybe Double
compute a b c = do
x <- safeDiv a b
y <- safeDiv x c
return (y + 1)
-- Equivalent without do:
-- compute a b c = safeDiv a b >>= \x -> safeDiv x c >>= \y -> Just (y + 1)
-- IO monad
main :: IO ()
main = do
putStrLn "Enter two numbers:"
a <- readLn
b <- readLn
case safeDiv a b of
Just r -> putStrLn $ "Result: " ++ show r
Nothing -> putStrLn "Cannot divide by zero"
-- Either for error messages
safeDivEither :: Double -> Double -> Either String Double
safeDivEither _ 0 = Left "Division by zero"
safeDivEither x y = Right (x / y)