ZetCode

F# computation expressions

last modified December 3, 2026

In this article we write our own computation expressions in F#.

A computation expression is a block of code of the form builder { ... }. Inside the braces we use ordinary F# code together with special keywords such as let!, return and yield. What those keywords do is decided by the builder, an object with methods of agreed names. The library comes with builders for sequences, lists, asynchronous code and tasks; we can write our own for options, results and anything else that is chained in the same way.

Expressions with a builder

We have already used computation expressions. A sequence expression is one: seq is the builder and for and yield get their meaning from it.

builtin.fsx
let squares = seq {
    for i in 1 .. 5 do
        yield i * i
}

let evens = [ for i in 1 .. 10 do if i % 2 = 0 then i ]

printfn "%A" (List.ofSeq squares)
printfn "%A" evens

The first expression produces a lazy sequence, the second a list.

let evens = [ for i in 1 .. 10 do if i % 2 = 0 then i ]

A list expression in square brackets is a computation expression with a built-in list builder. When the body has no other result, a value on its own is an implicit yield. These two builders are covered in F# sequences and F# list comprehensions.

λ dotnet fsi builtin.fsx
[1; 4; 9; 16; 25]
[2; 4; 6; 8; 10]

Nested options

Before we write a builder, we look at the problem it solves. Each step of the following calculation can fail, so each returns an option, and the next step runs only when the previous one gave a value.

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

let divide a b =
    if b = 0 then None else Some (a / b)

let calculate x y =
    match parseInt x with
    | None -> None
    | Some a ->
        match parseInt y with
        | None -> None
        | Some b ->
            match divide a b with
            | None -> None
            | Some q -> Some (q + 1)

printfn "%A" (calculate "84" "4")
printfn "%A" (calculate "84" "zero")
printfn "%A" (calculate "84" "0")

The program parses two numbers, divides them and adds one.

match parseInt x with
| None -> None
| Some a ->
    match parseInt y with

Every step repeats the same pattern: on None stop with None, on Some continue with the value. The real work is hidden in the growing indentation. Option.bind from F# option type removes the matching, but the nested lambdas remain.

λ dotnet fsi nested.fsx
Some 22
None
None

A first builder

A builder is an instance of a class. The class needs a Bind method for let! and a Return method for return.

builder.fsx
type OptionBuilder() =
    member _.Bind(x, f) = Option.bind f x
    member _.Return(x) = Some x

let option = OptionBuilder()

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

let divide a b =
    if b = 0 then None else Some (a / b)

let calculate x y =
    option {
        let! a = parseInt x
        let! b = parseInt y
        let! q = divide a b
        return q + 1
    }

printfn "%A" (calculate "84" "4")
printfn "%A" (calculate "84" "zero")
printfn "%A" (calculate "84" "0")

The calculation now reads like straight-line code and gives the same results as before.

type OptionBuilder() =
    member _.Bind(x, f) = Option.bind f x
    member _.Return(x) = Some x

Bind receives an option and the rest of the computation as a function. Option.bind calls that function only for Some. Return wraps the final value in Some. The class has no state; see F# classes for the syntax.

let option = OptionBuilder()

The builder object needs a name, which becomes the word in front of the braces. The name option does not clash with the option type, because types and values live in separate namespaces.

let! a = parseInt x

let! unwraps the option. If parseInt returns None, the rest of the block does not run and the whole expression is None.

λ dotnet fsi builder.fsx
Some 22
None
None

What the compiler does

The compiler translates a computation expression into calls of the builder methods. To see the calls, we add a printfn to each method.

trace.fsx
type TraceBuilder() =
    member _.Bind(x, f) =
        printfn "Bind %A" x
        Option.bind f x
    member _.Return(x) =
        printfn "Return %A" x
        Some x

let option = TraceBuilder()

let r1 = option {
    let! a = Some 6
    let! b = Some 7
    return a * b
}
printfn "result: %A" r1

let r2 = option {
    let! a = None
    let! b = Some 7
    return a * b
}
printfn "result: %A" r2

The first block calls every method, the second stops after the first Bind.

option.Bind(Some 6, fun a ->
    option.Bind(Some 7, fun b ->
        option.Return(a * b)))

This is what the first block becomes. Each let! turns into a Bind call whose second argument is a lambda holding the rest of the block. The nesting from the previous section is still there; the compiler writes it for us.

let! a = None

In the second block the first Bind receives None. Option.bind does not call the lambda, so neither the second Bind nor Return runs.

λ dotnet fsi trace.fsx
Bind Some 6
Bind Some 7
Return 42
result: Some 42
Bind None
result: None

A missing method

A builder only supports the constructs for which it has methods. An if without else needs a value for the missing branch, which comes from a method named Zero.

no_zero.fsx
type OptionBuilder() =
    member _.Bind(x, f) = Option.bind f x
    member _.Return(x) = Some x

let option = OptionBuilder()

let positive n = option {
    if n > 0 then
        return n
}

Our builder has only Bind and Return.

if n > 0 then
    return n

When n is not positive, the block has no result. The compiler does not invent one; it reports error FS0708 and names the method that is missing.

λ dotnet fsi no_zero.fsx
no_zero.fsx(8,5): error FS0708: This control construct may only be used if the computation expression builder defines a 'Zero' method

return! and Zero

We complete the option builder and put it into its own script file, so that later examples can load it with #load. Zero supplies the missing result and ReturnFrom implements return!, which returns an option as it is, without wrapping it again.

builders.fsx
type OptionBuilder() =
    member _.Bind(x, f) = Option.bind f x
    member _.Return(x) = Some x
    member _.ReturnFrom(x: 'a option) = x
    member _.Zero() = None

let option = OptionBuilder()

#load "builders.fsx" makes the file a module named Builders, as shown in F# modules and namespaces.

order.fsx
#load "builders.fsx"
open Builders

let stock = Map [ "apple", 12; "pear", 0; "plum", 5 ]
let prices = Map [ "apple", 0.5; "pear", 0.8; "plum", 1.2 ]

let costOf item qty =
    option {
        let! price = Map.tryFind item prices
        let! available = Map.tryFind item stock
        if qty <= available then
            return float qty * price
    }

let orderCost item qty =
    option {
        if qty = 0 then
            return 0.0
        else
            return! costOf item qty
    }

printfn "%A" (orderCost "apple" 10)
printfn "%A" (orderCost "plum" 8)
printfn "%A" (orderCost "kiwi" 1)
printfn "%A" (orderCost "kiwi" 0)

The order cost is known only when the item has a price and enough pieces are in stock.

if qty <= available then
    return float qty * price

When there are not enough pieces, the if has no else branch and the builder's Zero gives None.

return! costOf item qty

costOf already returns an option. With return we would get Some (Some 5.0); return! passes the inner option on unchanged. An order of zero pieces costs nothing, even for an unknown item.

λ dotnet fsi order.fsx
Some 5.0
None
None
Some 0.0

match!

match! unwraps a value with Bind and matches on the result in one step. It needs no new builder method.

match_bang.fsx
#load "builders.fsx"
open Builders

let settings = Map [ "verbose", "on"; "colour", "off"; "cache", "maybe" ]

let flag name =
    option {
        match! Map.tryFind name settings with
        | "on" -> return true
        | "off" -> return false
        | _ -> return! None
    }

for name in [ "verbose"; "colour"; "cache"; "debug" ] do
    printfn "%-8s %A" name (flag name)

The flag function reads a setting and turns it into a Boolean.

match! Map.tryFind name settings with

This is a shorter form of let! value = Map.tryFind name settings followed by match value with. A missing setting stops the computation before the match; an unknown value reaches the last case, which returns None with return!.

λ dotnet fsi match_bang.fsx
verbose  Some true
colour   Some false
cache    None
debug    None

A Result builder

The same three methods work for the Result type from F# Result type. A failed step stops the computation, and unlike an option it carries a message saying why.

result.fsx
type ResultBuilder() =
    member _.Bind(x, f) = Result.bind f x
    member _.Return(x) = Ok x
    member _.ReturnFrom(x: Result<_, _>) = x

let result = ResultBuilder()

type User = { Name: string; Age: int }

let validName (s: string) =
    if s.Trim() = "" then Error "name is empty" else Ok (s.Trim())

let validAge (s: string) =
    match System.Int32.TryParse s with
    | true, n when n >= 0 && n < 150 -> Ok n
    | true, n -> Error $"age {n} is out of range"
    | _ -> Error $"'{s}' is not a number"

let makeUser name age =
    result {
        let! n = validName name
        let! a = validAge age
        return { Name = n; Age = a }
    }

printfn "%A" (makeUser "Lucia" "34")
printfn "%A" (makeUser " " "34")
printfn "%A" (makeUser "Peter" "abc")
printfn "%A" (makeUser " " "200")

The program validates a name and an age and builds a record from them.

member _.Bind(x, f) = Result.bind f x

The only change from the option builder is the library function: Result.bind runs the rest of the computation for Ok and passes an Error on.

printfn "%A" (makeUser " " "200")

Both values are wrong in the last call, but we only learn about the name. The first error stops the computation, so the age is never checked.

λ dotnet fsi result.fsx
Ok { Name = "Lucia"
     Age = 34 }
Error "name is empty"
Error "'abc' is not a number"
Error "name is empty"

Collecting all errors with and!

When the values do not depend on each other, we can check all of them and report every error at once. and! combines independent values; the builder needs a MergeSources method that pairs two values and a BindReturn method that maps the result.

validation.fsx
type ValidationBuilder() =
    member _.BindReturn(x, f) = Result.map f x
    member _.MergeSources(a, b) =
        match a, b with
        | Ok x, Ok y -> Ok (x, y)
        | Error e1, Error e2 -> Error (e1 @ e2)
        | Error e, Ok _ -> Error e
        | Ok _, Error e -> Error e

let validation = ValidationBuilder()

type User = { Name: string; Age: int; Email: string }

let validName (s: string) =
    if s.Trim() = "" then Error [ "name is empty" ] else Ok (s.Trim())

let validAge n =
    if n >= 0 && n < 150 then Ok n else Error [ $"age {n} is out of range" ]

let validEmail (s: string) =
    if s.Contains "@" then Ok s else Error [ $"'{s}' is not an email" ]

let makeUser name age email =
    validation {
        let! n = validName name
        and! a = validAge age
        and! e = validEmail email
        return { Name = n; Age = a; Email = e }
    }

printfn "%A" (makeUser "Lucia" 34 "lucia@example.com")
printfn "%A" (makeUser " " 200 "lucia")

The errors are lists of strings, so that two errors can be joined.

| Error e1, Error e2 -> Error (e1 @ e2)

MergeSources receives two results. When both are errors, it concatenates the lists; when both succeed, it pairs the values in a tuple. The compiler calls it once for each and!, so three values become nested pairs.

member _.BindReturn(x, f) = Result.map f x

BindReturn handles a block that ends with return right after the let! and and! lines. It applies the final expression to the merged value. Because the builder has no Bind, a second let! that depends on the first is not possible here.

λ dotnet fsi validation.fsx
Ok { Name = "Lucia"
     Age = 34
     Email = "lucia@example.com" }
Error ["name is empty"; "age 200 is out of range"; "'lucia' is not an email"]

Producing values with yield

A builder can also collect values, as seq does. Yield makes a result from one value, Combine joins two results, and Delay wraps the parts of the body. For supports loops and Zero an empty else branch.

lines.fsx
type LinesBuilder() =
    member _.Yield(x: string) = [ x ]
    member _.Combine(a: string list, b: string list) = a @ b
    member _.Delay(f: unit -> string list) = f ()
    member _.Zero() : string list = []
    member _.For(xs: seq<'a>, f: 'a -> string list) =
        xs |> Seq.collect f |> List.ofSeq

let lines = LinesBuilder()

let items = [ "bread", 2.40; "milk", 1.10; "cheese", 4.75 ]

let receipt =
    lines {
        yield "RECEIPT"
        for name, price in items do
            yield sprintf "%-8s %6.2f" name price
        let total = List.sumBy snd items
        yield sprintf "%-8s %6.2f" "total" total
        if total > 5.0 then
            yield "free delivery"
    }

receipt |> List.iter (printfn "%s")

The builder produces a list of text lines for a receipt.

yield "RECEIPT"
for name, price in items do
    yield sprintf "%-8s %6.2f" name price

Each yield gives a one-element list. The for loop calls For, which runs the body for every item and joins the lists. Statements that follow each other are joined with Combine.

let total = List.sumBy snd items

An ordinary let may appear between the yield lines. Unlike let!, it needs no builder method.

λ dotnet fsi lines.fsx
RECEIPT
bread      2.40
milk       1.10
cheese     4.75
total      8.25
free delivery

Loops and Delay

In the yield builder Delay ran its function at once. For a builder that stops early, that is too soon: the rest of the block would run even after an error. Here Delay returns the function itself, Combine calls it only when the first part succeeded, and Run starts the whole computation. For stops at the first error. We save the extended builder in a file.

results.fsx
type ResultBuilder() =
    member _.Bind(x, f) = Result.bind f x
    member _.Return(x) = Ok x
    member _.ReturnFrom(x: Result<_, _>) = x
    member _.Zero() = Ok ()
    member _.Delay(f: unit -> Result<_, _>) = f
    member _.Run(f: unit -> Result<_, _>) = f ()
    member _.Combine(a: Result<unit, _>, b: unit -> Result<_, _>) =
        Result.bind b a
    member _.For(xs: seq<'a>, body: 'a -> Result<unit, _>) =
        let mutable state = Ok ()
        use e = xs.GetEnumerator()
        while Result.isOk state && e.MoveNext() do
            state <- body e.Current
        state

let result = ResultBuilder()

The new builder lets us validate the items of a list in a loop.

scores.fsx
#load "results.fsx"
open Results

let checkScore (s: string) =
    printfn "checking %s" s
    match System.Int32.TryParse s with
    | true, n when n >= 0 && n <= 100 -> Ok n
    | _ -> Error $"invalid score '{s}'"

let total scores =
    result {
        let mutable sum = 0
        for s in scores do
            let! n = checkScore s
            sum <- sum + n
        return sum
    }

printfn "%A" (total [ "70"; "85"; "90" ])
printfn "%A" (total [ "70"; "x"; "90" ])

The total function adds up scores given as text.

for s in scores do
    let! n = checkScore s
    sum <- sum + n

The loop body ends with an assignment, a unit value, so the compiler adds a call to Zero to give it the result Ok (). When checkScore fails, For ends the loop; the output shows that the third score of the second list is never checked.

return sum

The loop and the return are joined with Combine. Since the loop gave an error, the delayed return never runs and the error becomes the result.

λ dotnet fsi scores.fsx
checking 70
checking 85
checking 90
Ok 245
checking 70
checking x
Error "invalid score 'x'"

Reading a configuration

The last program uses the Result builder to read a small configuration format of key = value lines into a record. Blank lines and comments are skipped, the port is required and the number of retries has a default value.

config.fsx
#load "results.fsx"
open System
open Results

type Config = { Host: string; Port: int; Retries: int }

let parseLine (no: int) (line: string) =
    match line.Split('=', 2) with
    | [| key; value |] -> Ok (key.Trim(), value.Trim())
    | _ -> Error $"line {no}: expected key = value"

let parseNumber name (value: string) =
    match Int32.TryParse value with
    | true, n when n > 0 -> Ok n
    | _ -> Error $"{name}: '{value}' is not a positive number"

let required name settings =
    match Map.tryFind name settings with
    | Some value -> Ok value
    | None -> Error $"{name} is missing"

let parseConfig (lines: string list) =
    result {
        let mutable settings = Map.empty
        for no, line in List.indexed lines do
            let text = line.Trim()
            if text <> "" && not (text.StartsWith "#") then
                let! key, value = parseLine (no + 1) text
                settings <- Map.add key value settings
        let! host = required "host" settings
        let! port = required "port" settings |> Result.bind (parseNumber "port")
        let retries = Map.tryFind "retries" settings |> Option.defaultValue "3"
        let! retries = parseNumber "retries" retries
        return { Host = host; Port = port; Retries = retries }
    }

let show lines =
    match parseConfig lines with
    | Ok c -> printfn "ok: %s:%d, %d retries" c.Host c.Port c.Retries
    | Error e -> printfn "error: %s" e

show [ "# server"; "host = example.com"; "port = 8080" ]
show [ "host = example.com"; "port = 80"; "retries = 5" ]
show [ "host = example.com"; "port 8080" ]
show [ "host = example.com"; "port = http" ]
show [ "port = 8080" ]

The program parses five configurations, two good and three with errors.

let! key, value = parseLine (no + 1) text

A let! may take a pattern apart, here a tuple. A line without an equals sign stops the loop with an error that names the line. List.indexed numbers the lines from zero.

let! port = required "port" settings |> Result.bind (parseNumber "port")

Inside the builder we can still use the Result functions. The port must be present and must be a positive number.

let retries = Map.tryFind "retries" settings |> Option.defaultValue "3"
let! retries = parseNumber "retries" retries

A missing retries setting is not an error, so the lookup is an ordinary let with a default value. The second line shadows retries with the parsed number.

λ dotnet fsi config.fsx
ok: example.com:8080, 3 retries
ok: example.com:80, 5 retries
error: line 2: expected key = value
error: port: 'http' is not a positive number
error: host is missing

Source

F# language reference: Computation expressions

F# language reference: Sequences

In this article we have written computation expression builders for options, results, validation and lists of lines. We have seen how let! becomes a call to Bind, added return!, Zero and match!, collected errors with and!, and supported yield and loops with Combine, Delay and For. The library builders for asynchronous code are covered in F# async and tasks.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.