liveBook · Manning

Option

As explained in The Coder Cafe

Maybe is a Haskell type representing either an absent value or a present value of a specified type.

An option represents a value that may be present or absent. In Haskell, Maybe is this optional context: Just holds a value, while Nothing represents its absence. Similar concepts include Rust’s Option and Java’s Optional. section 3.2.1

The operation depends on where the function and value are:

  • Use fmap for a function outside Maybe: fmap (+ 1) (Just 42) produces Just 43, while mapping over Nothing leaves Nothing. section 3.2.1
  • Use <*> when the function is also wrapped: Just (+ 1) <*> Just 42 produces Just 43. Both sides must have the same applicative context. section 3.2.2

A computation that may have no result

A divide function can return Maybe Float: when the denominator is zero, it returns Nothing; otherwise, it wraps the quotient. The caller receives an explicit optional result rather than assuming division succeeded. section 3.2.3

Types still have to line up. In greet <$> Just name <*> validateAge age, the greeting function consumes only a name, but <*> is also given an optional age. This expression fails to compile because the wrapped function does not accept that additional Int argument. section 3.2.4

How The Coder Cafe covers it

How deep it goes
Works through mapping, wrapped functions, and optional results, then diagnoses an applicative type mismatch without completing the greeting implementation.
Examples
Uses mapping over Just and Nothing and an age-gated greeting expression that fails to type-check.
What it assumes
Introduces functors and applicatives through box analogies while using functions and Haskell-style type signatures.
What you can do after
Apply it via Haskell Maybe, fmap, and <*> to transform optional values and recognize incompatible function arguments.
How it connects
Connects functors, applicative functors, pattern matching, and monads through transformations involving Maybe.

Also explained in

Compare how 12 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.