jonnifyfsharp

Module C1.09 · the chapter lab

Computation expressions & async

Build a small language of your own, then run asynchronous work in it.

A computation expression is the something { ... } block: seq { }, async { }, and builders you write yourself. Inside the braces, let! and return are not keywords — they are calls to Bind and Return methods on a builder object. That one idea unifies a lot of F#: the chaining you saw with absence and failure, lazy sequences, and asynchronous work all become the same readable block. This module is the chapter's lab — the final dive has you write a builder by hand and watch it run, and short-circuit, over a type you already know.

One block syntax, three uses

The three dives move from the mechanism to the lab. The first names the mechanism: a CE block desugars to method calls on a builder — let! x = e becomes builder.Bind(e, fun x -> …), and return v becomes builder.Return(v). The built-in seq { } is a CE you have already used. The second covers async: async { } describes asynchronous work as a value, Async.RunSynchronously runs it, and Async.Parallel runs a list of them concurrently.

The third is the lab: write an OptionBuilder with Bind and Return, instantiate it as option, and run an option { … } block. A None anywhere in the chain short-circuits — Bind never calls the continuation — so the whole block is None without a single if. Select a dive below to read its summary and the result it works through.

The three dives · select one

C1.09.1 comp. expressions C1.09.2 async workflows C1.09.3 build your own the mechanism the lab
C1.09.1 · Computation expressions

A CE block desugars to Bind/Return calls on a builder. let! x = e becomes builder.Bind(e, fun x -> …); return v becomes builder.Return(v). seq { } is one you have already used.

key result seq { for x in 1..3 -> x * x } |> Seq.toList = [1; 4; 9]

Open this dive · or pick another above

A builder, two methods, one block: that is the whole machinery behind seq, async, and the option you build in the lab.

The three dives

Read them in order. Each stands on valid, runnable F#: every CE block, every desugaring, and every result below can be typed into dotnet fsi and prints exactly what the page shows. The third is the lab — a builder written from scratch.

live module hub built dive ready soon specified

References

Sources

Related in this course