F# · Lesson 10

Computation Expressions

seq, async and task blocks, list comprehensions, and writing your own option/result builders with let! and return.

7 min read

In short

  • A builder decides what let!, do!, yield and return mean
  • [ for ... ] and seq { } build lists and lazy sequences
  • let! is await; return is required
  • task { } is hot and returns a Task; async { } is cold
  • Your own builder needs just Bind and Return

What is a computation expression?

A computation expression (CE) is a block written builder { ... }. The code inside looks like normal F#, but the builder decides what the special keywords (let!, do!, yield, return) mean.

You already know two hard-wired versions of this idea from JavaScript: async/await and generator functions with yield. In F# they aren't special syntax baked into the language. They're library features, and you can write your own.

TypeScriptF#
array built with loops / map / filter[ for x in xs do if ... then yield ... ]
function* gen() { yield 1; yield* other(); }seq { yield 1; yield! other }
async function f() { const x = await g(); return x; }task { let! x = g () in return x } or async { ... }
user?.address?.cityoption { let! a = user.Address in return a.City } (custom builder)

List, array and seq comprehensions

▶ Try
const evenSquares: number[] = [];
for (const n of [1, 2, 3, 4]) {
  if (n % 2 === 0) evenSquares.push(n * n);
}
▶ Try
let evenSquares =
    [ for n in 1..4 do
          if n % 2 = 0 then
              yield n * n ]                 // [4; 16]

let squares = [ for n in 1..4 -> n * n ]    // `->` is short for `do yield`
let seats = [ for row in [ 'A'; 'B' ] do for n in 1..2 -> $"{row}{n}" ]
// ["A1"; "A2"; "B1"; "B2"]
  • [ ... ] builds a list, [| ... |] an array, seq { ... } a lazy sequence. The syntax inside is the same.
  • yield x emits one item. yield! xs emits every item of another collection (like yield* in JS).
  • Since F# 4.7 yield is implicit when it's unambiguous: [ for n in 1..4 do if n % 2 = 0 then n * n ].
  • let, match, if and nested for all work inside. Ranges can have a step: [ 0 .. 15 .. 59 ] is [0; 15; 30; 45].

seq { }: lazy sequences

seq<'T> is .NET's IEnumerable<'T>, the equivalent of a JS iterator or generator. Nothing runs until somebody iterates.

▶ Try
function* countFrom(n: number) {
  while (true) yield n++;
}
▶ Try
let rec countFrom (n: int) : seq<int> =
    seq {
        yield n
        yield! countFrom (n + 1) // infinite, but lazy: fine
    }

countFrom 5 |> Seq.take 3 |> Seq.toList // [5; 6; 7]

Laziness is easy to see with side effects:

▶ Try
let numbers =
    seq {
        printfn "computing 1"
        yield 1
        printfn "computing 2"
        yield 2
    }

numbers |> Seq.head // prints only "computing 1"
  • Seq.take, Seq.truncate, Seq.takeWhile and Seq.filter stay lazy; Seq.toList / List.ofSeq force everything.
  • A seq re-runs its code each time it's enumerated, like calling a generator function again. Use Seq.cache or convert to a list if it's expensive.

async { } and task { }

F# has two ways to write asynchronous code:

  • task { } produces a .NET Task<'T>, the equivalent of a JS Promise: it is hot and starts running immediately. Use it when you call or expose .NET APIs (ASP.NET Core, HttpClient, EF Core).
  • async { } produces an F# Async<'T>: it is cold, a recipe that only runs when started (Async.RunSynchronously, Async.Start, Async.StartAsTask). It composes nicely (Async.Parallel) and passes cancellation along implicitly. Use it for F#-first code.
▶ Try
async function getTotal(ids: string[]): Promise<number> {
  const prices = await Promise.all(ids.map(fetchPrice));
  await sleep(10);
  return prices.reduce((a, b) => a + b, 0);
}
▶ Try
let getTotal (ids: string list) : Async<decimal> =
    async {
        let! prices = ids |> List.map fetchPrice |> Async.Parallel // await Promise.all(...)
        do! Async.Sleep 10                                         // await something returning unit
        return Array.sum prices
    }

let total = getTotal [ "a"; "b" ] |> Async.RunSynchronously // block (scripts and tests only)

Line by line:

  • let! x = work is const x = await work: wait for the result and bind it.
  • do! work awaits something that returns unit (no value).
  • return value produces the final result. It is required: the last line is not returned automatically.
  • return! other returns another async's result, like return await other().
  • Async.Parallel turns a list of Async<'T> into one Async<'T[]>. They run concurrently and the results keep the input order.

The task version looks the same:

▶ Try
open System.Threading.Tasks

let getUserName (id: int) : Task<string> =
    task {
        do! Task.Delay 10
        return $"user-{id}"
    }

let name = (getUserName 1).Result // block in a script; in app code you'd `let!` it

Inside task { } you can let! both Tasks and Asyncs. Async.StartAsTask and Async.AwaitTask convert between the two. for loops, while, try/with and use all work inside both.

Writing your own builder

A builder is a class with specially named methods. To support let! and return you need just two:

▶ Try
type OptionBuilder() =
    member _.Bind(value: 'a option, rest: 'a -> 'b option) : 'b option =
        match value with
        | Some x -> rest x // continue with the unwrapped value
        | None -> None     // short-circuit: skip the rest of the block

    member _.Return(x: 'a) : 'a option = Some x
    member _.ReturnFrom(x: 'a option) : 'a option = x // enables `return!`

let option = OptionBuilder()

Using it:

▶ Try
const city = findUser(id)?.address?.city;
▶ Try
let cityOf (userId: int) : string option =
    option {
        let! user = tryFindUser userId // None here stops everything
        let! address = user.Address
        return address.City
    }

The compiler rewrites the block into calls on the builder:

▶ Try
option.Bind(tryFindUser userId, fun user ->
    option.Bind(user.Address, fun address ->
        option.Return(address.City)))

That's exactly the nested Option.bind pyramid from the Option and Result topic, flattened for you. A result { } builder is the same pattern with Ok/Error, and it turns a railway of Result.bind calls into straight-line code:

▶ Try
let register (form: Form) : Result<User, SignupError> =
    result {
        let! name = validateName form.Name
        let! email = validateEmail form.Email
        return { Name = name; Email = email }
    }

In real projects you'll usually get these builders from the FsToolkit.ErrorHandling library (option { }, result { }, taskResult { }, validation { }). Writing one yourself once shows there's no magic. Other builder methods (Zero, Combine, Delay, For, While, TryWith, Using) unlock more syntax inside the block.

Common beginner mistakes

  • Forgetting return. The block then has type unit, and you get "expected Async<int> but here has type Async<unit>".
  • let instead of let!. You get the wrapped Async<int> instead of the int.
  • let!, do! or return outside a CE. do! and return give "This construct may only be used within computation expressions"; a stray let! can even slip through as a plain let, so you end up holding the wrapped value.
  • Blocking with .Result / Async.RunSynchronously inside async code. It can deadlock or starve the thread pool. Only block at the very top (scripts, tests, main).
  • Assuming async { } runs when created. It's cold. Only task { } starts immediately.
  • Enumerating an expensive seq several times. Each enumeration redoes the work.
  • Mixing up yield and return. Sequences and lists yield; async, task, option and result return.

Cheat sheet

▶ Try
[ for x in xs do if p x then yield f x ]  // list comprehension; [| |] for arrays
[ for x in xs -> f x ]                    // map shorthand
seq { yield 1; yield! more }              // lazy; force with Seq.toList
async {                                   // Async<'T>, cold
    let! x = a
    do! b
    return x }
task { let! x = t in return x }           // Task<'T>, hot (one line needs `in`)
Async.RunSynchronously a  /  t.Result     // block: scripts/tests only
Async.Parallel [ a1; a2 ]                 // Async<'T[]>, order preserved
Async.Sleep 10  /  Task.Delay 10          // delays
type B() =
    member _.Bind(m, f) = ...
    member _.Return(x) = ...
let b = B()                               // then: b { let! x = m in return x }

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app