liveBook · Manning

Option computation expression

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

An option computation expression sequences computations that may produce an optional value and propagates absence without requiring explicit unwrapping.

An option computation expression keeps a sequence of optional computations readable. Instead of manually unwrapping each value, write code that follows the successful, or “happy,” path while absence propagates automatically. section 9.3

Inside an option { } block:

  • Use let! to unwrap Some values and bind their contents. section 9.3
  • Return None immediately when any computation produces None. section 9.3

Parsing three numbers

Manual pattern matching must check every parsed option before calling calc. The option expression instead lets each parse succeed in sequence: let! numberOne = tryParseNumber "1", followed by the other values, then return calc numberOne numberTwo numberThree.

#r "nuget:FSToolkit.ErrorHandling, 2.13.0"          #1
open FsToolkit.ErrorHandling                        #1
 
let myMaybeData = option {                          #2
    let! numberOne = tryParseNumber "1"             #3
    let! numberTwo = tryParseNumber "2"             #3
    let! numberThree = tryParseNumber "3"           #3
    return calc numberOne numberTwo numberThree     #4
}

Browse the complete F# example, including the FsToolkit.ErrorHandling package reference, option block, let! bindings, and final calculation. section 9.3

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

How deep it goes
Explains let! as compiler-managed pattern matching and shows propagation, without descending into computation-expression implementation internals.
Examples
Demonstrates parsing three numbers, manually pattern matching them, and calculating with an option computation expression.
What it assumes
Assumes familiarity with optional values and parsing functions, while demonstrating the sequencing and unwrapping pattern directly.
What you can do after
Apply it via FsToolkit.ErrorHandling to sequence optional computations without explicit unwrapping or repeated absence checks.
How it connects
Connects optional values with pattern matching, Option.map, bind, and computation expressions.

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.