Esc
Start typing to search...

Maybe Module

Functions for working with Maybe values — composable optional handling.

Maybe represents a value that may or may not exist (Just value or Nothing). The Maybe module provides pipe-friendly functions for transforming, chaining, and extracting Maybe values without explicit pattern matching.

Common patterns

import Maybe

-- Transform the inner value
Just 5 |> Maybe.map (|x| x * 2)           -- Just 10
Nothing |> Maybe.map (|x| x * 2)          -- Nothing

-- Chain operations that may return Nothing
let safeSqrt = |x| if x >= 0.0 then Just (sqrt x) else Nothing
Just 16.0 |> Maybe.andThen safeSqrt       -- Just 4.0
Just (-1.0) |> Maybe.andThen safeSqrt     -- Nothing
Nothing |> Maybe.andThen safeSqrt         -- Nothing

-- Extract with a default
Just 42 |> Maybe.withDefault 0             -- 42
Nothing |> Maybe.withDefault 0             -- 0

Maybe vs Result

Maybe signals whether a value exists, without explaining why it might be absent. Result carries an error value with the reason for failure.

MaybeResult
PresentJust valueOk value
AbsentNothingErr reason
Error infoNoYes

Use Maybe for lookups, optional fields, and operations where absence is expected and needs no explanation (List.head, String.toInt). Use Result when the caller needs to know what went wrong. Convert with Result.toMaybe and Result.fromMaybe.

Functions

Transforming

Maybe.map

(a -> b) -> Maybe a -> Maybe b

Transform the Just value of a Maybe. If the Maybe is Nothing, it is passed through unchanged.

Example:
import Maybe

(Just 5) |> Maybe.map (|x| x + 1)
Try it

See also: Maybe.andThen, Maybe.withDefault

Chaining

Maybe.andThen

(a -> Maybe b) -> Maybe a -> Maybe b

Chain a Maybe-producing function. If the Maybe is Just, apply the function to the value. If Nothing, pass through.

Example:
import Maybe

(Just 5) |> Maybe.andThen (|x| if x > 0 then Just (x * 2) else Nothing)
Try it

Notes: Useful for chaining operations that may not return a value.

See also: Maybe.map

Extracting

Maybe.withDefault

a -> Maybe a -> a

Extract the Just value, or use the provided default if the Maybe is Nothing.

Example:
import Maybe

Nothing
    |> Maybe.withDefault 0

-- 0
Try it

See also: Maybe.map