Skip to content
Option and Result Chains
step 1/4

Reading — step 1 of 4

Learn

~1 min readOption/Result and Async

F# uses Option<T> (Some x or None) and Result<T, E> (Ok x or Error e) for safe error handling — no exceptions for control flow.

Option chain — for "value or missing":

let tryParseInt (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None

// Pipeline:
let result =
    "42"
    |> tryParseInt
    |> Option.map (fun n -> n * 2)
    |> Option.defaultValue 0
// 84

Common Option ops:

  • Option.map f — transform the value if Some
  • Option.bind f — chain (flatMap)
  • Option.defaultValue x — unwrap with fallback
  • Option.iter f — side effect if Some
  • Option.toList / Option.toArray

Result chain — for "value or typed error":

let validateAge (s: string) : Result<int, string> =
    match tryParseInt s with
    | None -> Error "not a number"
    | Some n when n < 0 -> Error "negative"
    | Some n -> Ok n

match validateAge "25" with
| Ok n -> printfn "age: %d" n
| Error msg -> printfn "error: %s" msg

Result.bind for chaining fallible operations:

let parseAndDouble s =
    s
    |> validateAge
    |> Result.bind (fun n ->
        if n > 200 then Error "too old" else Ok (n * 2))

Computation expressions make these chains read like sequential code (next lesson).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…