BudiBadu Logo
Samplebadu

Haskell by Example: Maybe Type

GHC 9.x

Handling optional values safely with this sample code demonstrating Maybe type with Just and Nothing constructors, pattern matching for value extraction, monadic do notation for chaining operations, and eliminating null pointer exceptions.

Code

-- Safe division that returns Nothing on divide by zero
safeDiv :: Double -> Double -> Maybe Double
safeDiv _ 0 = Nothing
safeDiv x y = Just (x / y)

-- Handling the result
processResult :: Maybe Double -> String
processResult Nothing = "Error: Division by zero"
processResult (Just val) = "Result is: " ++ show val

-- Chaining Maybe operations (using do notation)
compute :: Double -> Double -> Double -> Maybe Double
compute a b c = do
    r1 <- safeDiv a b
    r2 <- safeDiv r1 c
    return r2

Explanation

The Maybe type in Haskell represents optional values, eliminating null pointer exceptions by making the absence of a value explicit in the type system. Defined as data Maybe a = Just a | Nothing, it has two constructors: Just a containing a value of type a, and Nothing representing absence. This forces explicit handling of missing values, preventing an entire class of runtime errors.

Maybe type characteristics include:

  • Just a constructor wraps a value, indicating presence
  • Nothing constructor represents absence without carrying data
  • Pattern matching extracts values safely, forcing error case handling
  • Maybe is a Monad, enabling composition with >>= bind operator
  • Functions like fromMaybe provide default values for Nothing cases

The Maybe monad allows chaining operations using do notation, where if any step returns Nothing, the entire computation short-circuits and returns Nothing, skipping subsequent steps. This eliminates nested conditional checks for error handling. The <- operator in do blocks extracts values from Just, automatically propagating Nothing through the chain.

Code Breakdown

2
Maybe Double return type wraps result in optional context.
3
Nothing represents failure case without error message.
4
Just (x / y) wraps successful result in Just constructor.
14
r1 <- safeDiv a b extracts value, short-circuits on Nothing.