liveBook · Manning

Option

As explained in Functional Design and Architecture: Examples in Haskell

The Maybe type is an algebraic data type representing either an optional value or the absence of a value.

An option represents a value that may be present or absent. The Maybe type makes both outcomes explicit: Just a contains a value, while Nothing represents no value. section 1.3.3

The design becomes useful when ordinary results can fail. A database lookup, name extraction, or first-letter operation can each return Maybe, so callers must account for missing data instead of assuming success. section 1.5.4

Mapping optional names

A list of possible names can be represented as [Maybe String]. Mapping length through the list and then through each Maybe produces [Just 5, Just 3, Nothing]. The list structure and each optional-value structure are preserved. section 1.3.3

Without monadic composition, chained lookups require nested case expressions that repeatedly propagate Nothing. Maybe's monadic behavior hides that plumbing: do notation sequences successful results and stops when any step is absent. section 1.5.4

getUserInitials' :: Int -> Maybe Char
getUserInitials' key = do
  user <- getUser key users       #1
  name <- getUserName user        #2
  Just (head name)

The compact do-notation example follows a user lookup, name lookup, and final character construction while preserving Maybe failure behavior. section 1.5.4

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Defines Just and Nothing, demonstrates fmap over nested structures, and refactors nested pattern matching with monadic do notation.
Examples
Uses optional names, nested fmap, database user lookup, name extraction, and initial-letter construction.
What it assumes
Assumes familiarity with lists and functions while introducing Maybe, functor behavior, monadic composition, and pattern matching through examples.
What you can do after
Apply via fmap and do notation to transform and sequence computations that may produce Nothing.
How it connects
Connects optional values to functors, fmap, monads, pattern matching, lists, and functional design.

Also explained in

Compare how 9 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.