Haskell
Maybe and IO Monads
Use Maybe for safety and IO for side effects.
By EZ4Code Team
monadmaybeio
Code
-- 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)Explanation
Maybe represents nullable values (Just x | Nothing). >>= (bind) chains computations that may fail — short-circuits on Nothing. do notation is sugar for >>= chains. IO isolates side effects — you can't escape IO in pure code. Either adds error info (Left err | Right val). The type system ensures safety: you can't forget to handle Nothing.
More Haskell Snippets
Types and Type Classes
Define algebraic data types and type classes.
List Comprehensions and Laziness
Generate lists with comprehensions and leverage laziness.
Functors, Applicatives, Monad Type Classes
The three core abstraction type classes.
IO and do Notation
Side-effectful programming in Haskell.
Modules and Imports
Organize code with modules and control exports.
Laziness and Strictness
Understand lazy evaluation and when to be strict.