Computation Expressions
Computation expressions (CEs) give a unified syntax (let!, do!, return, yield, use!, match!, for, while, try) for workflows: sequences, async, tasks, options, results, queries, and custom DSLs.
List/array comprehensions F# async workflows (cold, cancellable).NET Task (hot; best for ASP.NET interop)
result, option, validation, asyncResult, taskResult (FsToolkit), parser (FParsec), html DSLs, cancellableTask (IcedTasks)
// seq with yield, yield!, loops, conditions
let numbers = seq {
yield 1
yield! [2; 3]
for i in 4 .. 6 do
if i % 2 = 0 then yield i * 10
} // 1, 2, 3, 40, 60
// query expressions (LINQ)
let people = [ ("Ana", 30); ("Bo", 25); ("Cy", 41) ]
let adults = query {
for (name, age) in people do
where (age > 26)
sortBy name
select name
} // seq ["Ana"; "Cy"]
// match! binds and matches in one step
let describeFetch = async {
match! async { return Some 42 } with
| Some v -> return $"got {v}"
| None -> return "nothing"
}
// and! (applicative binding) works with builders that implement MergeSources/BindReturn,
// e.g. FsToolkit.ErrorHandling's validation { } or IcedTasks' parallel builders:
// validation { let! a = vName n and! b = vAge a return mkPerson a b }