liveBook · Manning

Option.map

As explained in F# in Action: A Revised Edition of Get Programming with F#

Option.map is an F# library function that applies a function to the value in a Some case and returns None unchanged, wrapping a successful result in Some.

Working with optional data often creates repetitive pattern matches: unwrap a Some value, apply the business logic, then wrap the result again. Option.map removes that boilerplate while preserving the possibility of None. section 9.1.3

Option.map takes a function for the Some case. It applies that function when a value exists, wraps the result in Some, and leaves None unchanged. Ordinary functions therefore work with optional values without knowing about options. section 9.1.3

A manual transformation can be reduced to a pipeline:

  • Verbose form: match customer with | Some c -> Some c.Age | None -> None. section 9.1.3
  • Idiomatic form: customer |> Option.map (fun c -> c.Age). section 9.1.3
  • Chain transformations with customer |> Option.map getAge |> Option.map classifyAge; each step continues only when the option contains Some. section 9.1.3

Compose before mapping

When getAge returns an int and classifyAge accepts an int, combine them as optionalCustomer |> Option.map (getAge >> classifyAge). This maps the option once and keeps getAge and classifyAge independent of optionality. section 9.1.3

Figure 9.2 A pipeline of operations over optional data

Trace how a pipeline of operations transforms optional data while preserving the option container. section 9.1.3

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains unwrapping, mapping, rewrapping, chaining, and composition, but defers deeper treatment to Option.bind.
Examples
Uses customer ages, age classification, manual matches, chained pipelines, and composed functions.
What it assumes
Assumes familiarity with F# functions, options, Some and None, and basic pattern matching.
What you can do after
Apply it via F# pipelines to transform Some values without manually unwrapping and rewrapping options.
How it connects
Connects Option.map with Option, Option.bind, pattern matching, function composition, Result, and exceptions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.