F# · Lesson 10
Computation Expressions
seq, async and task blocks, list comprehensions, and writing your own option/result builders with let! and return.
In short
- A builder decides what
let!,do!,yieldandreturnmean [ for ... ]andseq { }build lists and lazy sequenceslet!is await;returnis requiredtask { }is hot and returns a Task;async { }is cold- Your own builder needs just
BindandReturn
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.
| TypeScript | F# |
|---|---|
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?.city | option { let! a = user.Address in return a.City } (custom builder) |
List, array and seq comprehensions
const evenSquares: number[] = [];
for (const n of [1, 2, 3, 4]) {
if (n % 2 === 0) evenSquares.push(n * n);
}
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 xemits one item.yield! xsemits every item of another collection (likeyield*in JS).- Since F# 4.7
yieldis implicit when it's unambiguous:[ for n in 1..4 do if n % 2 = 0 then n * n ]. let,match,ifand nestedforall 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.
function* countFrom(n: number) {
while (true) yield n++;
}
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:
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.takeWhileandSeq.filterstay lazy;Seq.toList/List.ofSeqforce everything.- A
seqre-runs its code each time it's enumerated, like calling a generator function again. UseSeq.cacheor convert to a list if it's expensive.
async { } and task { }
F# has two ways to write asynchronous code:
task { }produces a .NETTask<'T>, the equivalent of a JSPromise: 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.
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);
}
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 = workisconst x = await work: wait for the result and bind it.do! workawaits something that returnsunit(no value).return valueproduces the final result. It is required: the last line is not returned automatically.return! otherreturns another async's result, likereturn await other().Async.Parallelturns a list ofAsync<'T>into oneAsync<'T[]>. They run concurrently and the results keep the input order.
The task version looks the same:
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:
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:
const city = findUser(id)?.address?.city;
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:
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:
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 typeunit, and you get "expected Async<int> but here has type Async<unit>". letinstead oflet!. You get the wrappedAsync<int>instead of theint.let!,do!orreturnoutside a CE.do!andreturngive "This construct may only be used within computation expressions"; a straylet!can even slip through as a plainlet, so you end up holding the wrapped value.- Blocking with
.Result/Async.RunSynchronouslyinside 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. Onlytask { }starts immediately. - Enumerating an expensive
seqseveral times. Each enumeration redoes the work. - Mixing up
yieldandreturn. Sequences and listsyield;async,task,optionandresultreturn.
Cheat sheet
[ 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