GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing learn.microsoft.com — Computation Expressions - F# Note Access to this page requires authorization. You can try signing in or changing directories. Access to this page requires authorization. You can try changing directories. Computation ExpressionsComputation expressions in F# provide a convenient syntax for writing computations that can be sequenced and combined using control flow constructs and bindings. Depending on the kind of computation expression, they can be thought of as a way to express monads, monoids, monad transformers, and applicative functors. However, unlike other languages (such as do-notation in Haskell), they are not tied to a single abstraction, and do not rely on macros or other forms of metaprogramming to accomplish a convenient and context-sensitive syntax. OverviewComputations can take many forms. The most common form of computation is single-threaded execution, which is easy to understand and modify. However, not all forms of computation are as straightforward as single-threaded execution. Some examples include:
More generally, there are context-sensitive computations that you must perform in certain parts of an application. Writing context-sensitive code can be challenging, as it is easy to "leak" computations outside of a given context without abstractions to prevent you from doing so. These abstractions are often challenging to write by yourself, which is why F# has a generalized way to do so called computation expressions. Computation expressions offer a uniform syntax and abstraction model for encoding context-sensitive computations. Every computation expression is backed by a builder type. The builder type defines the operations that are available for the computation expression. See Creating a New Type of Computation Expression, which shows how to create a custom computation expression. Syntax overviewAll computation expressions have the following form:
In this form,
There is a special, additional syntax available within a computation expression, as shown in the previous example. The following expression forms are possible with computation expressions:
Each of these keywords, and other standard F# keywords are only available in a computation expression if they have been defined in the backing builder type. The only exception to this is The builder type is an object that defines special methods that govern the way the fragments of the computation expression are combined; that is, its methods control how the computation expression behaves. Another way to describe a builder class is to say that it enables you to customize the operation of many F# constructs, such as loops and bindings.
|
| Method | Typical signature(s) | Description |
|---|---|---|
Bind |
M<'T> * ('T -> M<'U>) -> M<'U> |
Called for let! and do! in computation expressions. |
BindN |
(M<'T1> * M<'T2> * ... * M<'TN> * ('T1 * 'T2 ... * 'TN -> M<'U>)) -> M<'U> |
Called for efficient let! and and! in computation expressions without merging inputs.for example, Bind3, Bind4. |
Delay |
(unit -> M<'T>) -> Delayed<'T> |
Wraps a computation expression as a function. Delayed<'T> can be any type, commonly M<'T> or unit -> M<'T> are used. The default implementation returns a M<'T>. |
Return |
'T -> M<'T> |
Called for return in computation expressions. |
ReturnFrom |
M<'T> -> M<'T> |
Called for return! in computation expressions. |
ReturnFromFinal |
M<'T> -> M<'T> |
If present, called for return! and do! when in tail-call position. |
BindReturn |
(M<'T1> * ('T1 -> 'T2)) -> M<'T2> |
Called for an efficient let! ... return in computation expressions. |
BindNReturn |
(M<'T1> * M<'T2> * ... * M<'TN> * ('T1 * 'T2 ... * 'TN -> M<'U>)) -> M<'U> |
Called for efficient let! ... and! ... return in computation expressions without merging inputs.for example, Bind3Return, Bind4Return. |
MergeSources |
(M<'T1> * M<'T2>) -> M<'T1 * 'T2> |
Called for and! in computation expressions. |
MergeSourcesN |
(M<'T1> * M<'T2> * ... * M<'TN>) -> M<'T1 * 'T2 * ... * 'TN> |
Called for and! in computation expressions, but improves efficiency by reducing the number of tupling nodes.for example, MergeSources3, MergeSources4. |
Run |
Delayed<'T> -> M<'T> orM<'T> -> 'T |
Executes a computation expression. |
Combine |
M<'T> * Delayed<'T> -> M<'T> orM<unit> * M<'T> -> M<'T> |
Called for sequencing in computation expressions. |
For |
seq<'T> * ('T -> M<'U>) -> M<'U> orseq<'T> * ('T -> M<'U>) -> seq<M<'U>> |
Called for for...do expressions in computation expressions. |
TryFinally |
Delayed<'T> * (unit -> unit) -> M<'T> |
Called for try...finally expressions in computation expressions. |
TryWith |
Delayed<'T> * (exn -> M<'T>) -> M<'T> |
Called for try...with expressions in computation expressions. |
Using |
'T * ('T -> M<'U>) -> M<'U> when 'T :> IDisposable |
Called for use bindings in computation expressions. |
While |
(unit -> bool) * Delayed<'T> -> M<'T>or(unit -> bool) * Delayed<unit> -> M<unit> |
Called for while...do expressions in computation expressions. |
Yield |
'T -> M<'T> |
Called for yield expressions in computation expressions. |
YieldFrom |
M<'T> -> M<'T> |
Called for yield! expressions in computation expressions. |
YieldFromFinal |
M<'T> -> M<'T> |
If present, called for yield! when in tail-call position and in case of do! in tail-call position as a fallback for ReturnFromFinal |
Zero |
unit -> M<'T> |
Called for empty else branches of if...then expressions in computation expressions. |
Quote |
Quotations.Expr<'T> -> Quotations.Expr<'T> |
Indicates that the computation expression is passed to the Run member as a quotation. It translates all instances of a computation into a quotation. |
Many of the methods in a builder class use and return an M<'T> construct, which is typically a separately defined type that characterizes the kind of computations being combined, for example, Async<'T> for async expressions and Seq<'T> for sequence workflows. The signatures of these methods enable them to be combined and nested with each other, so that the workflow object returned from one construct can be passed to the next.
Many functions use the result of Delay as an argument: Run, While, TryWith, TryFinally, and Combine. The Delayed<'T> type is the return type of Delay and consequently the parameter to these functions. Delayed<'T> can be an arbitrary type that does not need to be related to M<'T>; commonly M<'T> or (unit -> M<'T>) are used. The default implementation is M<'T>. For a more in-depth look, see Understanding the type constraints.
The compiler, when it parses a computation expression, translates the expression into a series of nested function calls by using the methods in the preceding table and the code in the computation expression. The nested expression is of the following form:
builder.Run(builder.Delay(fun () -> {{ cexpr }}))
In the above code, the calls to Run and Delay are omitted if they are not defined in the computation expression builder class. The body of the computation expression, here denoted as {{ cexpr }}, is translated into further calls to the methods of the builder class. This process is defined recursively according to the translations in the following table. Code within double brackets {{ ... }} remains to be translated, expr represents an F# expression and cexpr represents a computation expression.
| Expression | Translation |
|---|---|
{{ let binding in cexpr }} |
let binding in {{ cexpr }} |
{{ let! pattern = expr in cexpr }} |
builder.Bind(expr, (fun pattern -> {{ cexpr }})) |
{{ do! expr in cexpr }} |
builder.Bind(expr, (fun () -> {{ cexpr }})) |
{{ yield expr }} |
builder.Yield(expr) |
{{ yield! expr }} |
builder.YieldFrom(expr) |
{{ return expr }} |
builder.Return(expr) |
{{ return! expr }} |
builder.ReturnFrom(expr) |
{{ use pattern = expr in cexpr }} |
builder.Using(expr, (fun pattern -> {{ cexpr }})) |
{{ use! value = expr in cexpr }} |
builder.Bind(expr, (fun value -> builder.Using(value, (fun value -> {{ cexpr }})))) |
{{ if expr then cexpr0 }} |
if expr then {{ cexpr0 }} else builder.Zero() |
{{ if expr then cexpr0 else cexpr1 }} |
if expr then {{ cexpr0 }} else {{ cexpr1 }} |
{{ match expr with | pattern_i -> cexpr_i }} |
match expr with | pattern_i -> {{ cexpr_i }} |
{{ for pattern in enumerable-expr do cexpr }} |
builder.For(enumerable-expr, (fun pattern -> {{ cexpr }})) |
{{ for identifier = expr1 to expr2 do cexpr }} |
builder.For([expr1..expr2], (fun identifier -> {{ cexpr }})) |
{{ while expr do cexpr }} |
builder.While(fun () -> expr, builder.Delay({{ cexpr }})) |
{{ try cexpr with | pattern_i -> expr_i }} |
builder.TryWith(builder.Delay({{ cexpr }}), (fun value -> match value with | pattern_i -> expr_i | exn -> System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exn).Throw())) |
{{ try cexpr finally expr }} |
builder.TryFinally(builder.Delay({{ cexpr }}), (fun () -> expr)) |
{{ cexpr1; cexpr2 }} |
builder.Combine({{ cexpr1 }}, {{ cexpr2 }}) |
{{ other-expr; cexpr }} |
expr; {{ cexpr }} |
{{ other-expr }} |
expr; builder.Zero() |
In the previous table, other-expr describes an expression that is not otherwise listed in the table. A builder class does not need to implement all of the methods and support all of the translations listed in the previous table. Those constructs that are not implemented are not available in computation expressions of that type. For example, if you do not want to support the use keyword in your computation expressions, you can omit the definition of Use in your builder class.
The following code example shows a computation expression that encapsulates a computation as a series of steps that can be evaluated one step at a time. A discriminated union type, OkOrException, encodes the error state of the expression as evaluated so far. This code demonstrates several typical patterns that you can use in your computation expressions, such as boilerplate implementations of some of the builder methods.
/// Represents computations that can be run step by step
type Eventually<'T> =
| Done of 'T
| NotYetDone of (unit -> Eventually<'T>)
module Eventually =
/// Bind a computation using 'func'.
let rec bind func expr =
match expr with
| Done value -> func value
| NotYetDone work -> NotYetDone (fun () -> bind func (work()))
/// Return the final value
let result value = Done value
/// The catch for the computations. Stitch try/with throughout
/// the computation, and return the overall result as an OkOrException.
let rec catch expr =
match expr with
| Done value -> result (Ok value)
| NotYetDone work ->
NotYetDone (fun () ->
let res = try Ok(work()) with | exn -> Error exn
match res with
| Ok cont -> catch cont // note, a tailcall
| Error exn -> result (Error exn))
/// The delay operator.
let delay func = NotYetDone (fun () -> func())
/// The stepping action for the computations.
let step expr =
match expr with
| Done _ -> expr
| NotYetDone func -> func ()
/// The tryFinally operator.
/// This is boilerplate in terms of "result", "catch", and "bind".
let tryFinally expr compensation =
catch (expr)
|> bind (fun res ->
compensation();
match res with
| Ok value -> result value
| Error exn -> raise exn)
/// The tryWith operator.
/// This is boilerplate in terms of "result", "catch", and "bind".
let tryWith exn handler =
catch exn
|> bind (function Ok value -> result value | Error exn -> handler exn)
/// The whileLoop operator.
/// This is boilerplate in terms of "result" and "bind".
let rec whileLoop pred body =
if pred() then body |> bind (fun _ -> whileLoop pred body)
else result ()
/// The sequential composition operator.
/// This is boilerplate in terms of "result" and "bind".
let combine expr1 expr2 =
expr1 |> bind (fun () -> expr2)
/// The using operator.
/// This is boilerplate in terms of "tryFinally" and "Dispose".
let using (resource: #System.IDisposable) func =
tryFinally (func resource) (fun () -> resource.Dispose())
/// The forLoop operator.
/// This is boilerplate in terms of "catch", "result", and "bind".
let forLoop (collection:seq<_>) func =
let ie = collection.GetEnumerator()
tryFinally
(whileLoop
(fun () -> ie.MoveNext())
(delay (fun () -> let value = ie.Current in func value)))
(fun () -> ie.Dispose())
/// The builder class.
type EventuallyBuilder() =
member x.Bind(comp, func) = Eventually.bind func comp
member x.Return(value) = Eventually.result value
member x.ReturnFrom(value) = value
member x.Combine(expr1, expr2) = Eventually.combine expr1 expr2
member x.Delay(func) = Eventually.delay func
member x.Zero() = Eventually.result ()
member x.TryWith(expr, handler) = Eventually.tryWith expr handler
member x.TryFinally(expr, compensation) = Eventually.tryFinally expr compensation
member x.For(coll:seq<_>, func) = Eventually.forLoop coll func
member x.Using(resource, expr) = Eventually.using resource expr
let eventually = new EventuallyBuilder()
let comp =
eventually {
for x in 1..2 do
printfn $" x = %d{x}"
return 3 + 4
}
/// Try the remaining lines in F# interactive to see how this
/// computation expression works in practice.
let step x = Eventually.step x
// returns "NotYetDone <closure>"
comp |> step
// prints "x = 1"
// returns "NotYetDone <closure>"
comp |> step |> step
// prints "x = 1"
// prints "x = 2"
// returns "Done 7"
comp |> step |> step |> step |> step
A computation expression has an underlying type, which the expression returns. The underlying type may represent a computed result or a delayed computation that can be performed, or it may provide a way to iterate through some type of collection. In the previous example, the underlying type was Eventually<_>. For a sequence expression, the underlying type is System.Collections.Generic.IEnumerable<T>. For a query expression, the underlying type is System.Linq.IQueryable. For an async expression, the underlying type is Async. The Async object represents the work to be performed to compute the result. For example, you call Async.RunSynchronously to execute a computation and return the result.
You can define a custom operation on a computation expression and use a custom operation as an operator in a computation expression. For example, you can include a query operator in a query expression. When you define a custom operation, you must define the Yield and For methods in the computation expression. To define a custom operation, put it in a builder class for the computation expression, and then apply the CustomOperationAttribute. This attribute takes a string as an argument, which is the name to be used in a custom operation. This name comes into scope at the start of the opening curly brace of the computation expression. Therefore, you shouldn't use identifiers that have the same name as a custom operation in this block. For example, avoid the use of identifiers such as all or last in query expressions.
If you already have a builder class, its custom operations can be extended from outside of this builder class. Extensions must be declared in modules. Namespaces cannot contain extension members except in the same file and the same namespace declaration group where the type is defined.
The following example shows the extensions of the existing FSharp.Linq.QueryBuilder class.
open System
open FSharp.Linq
type QueryBuilder with
[<CustomOperation>]
member _.any (source: QuerySource<'T, 'Q>, predicate) =
System.Linq.Enumerable.Any (source.Source, Func<_,_>(predicate))
[<CustomOperation("singleSafe")>] // you can specify your own operation name in the constructor
member _.singleOrDefault (source: QuerySource<'T, 'Q>, predicate) =
System.Linq.Enumerable.SingleOrDefault (source.Source, Func<_,_>(predicate))
Custom operations can be overloaded. For more information, see F# RFC FS-1056 - Allow overloads of custom keywords in computation expressions.
F# computation expressions that suspend execution can be compiled to highly efficient state machines through careful use of a low-level feature called resumable code. Resumable code is documented in F# RFC FS-1087 and used for Task Expressions.
F# computation expressions that are synchronous (that is, they don't suspend execution) can alternatively be compiled to efficient state machines by using inline functions including the InlineIfLambda attribute. Examples are given in F# RFC FS-1098.
List expressions, array expressions, and sequence expressions are given special treatment by the F# compiler to ensure generation of high-performance code.
For a custom builder, an explicit tail return! can use ReturnFromFinal and an explicit tail yield! can use YieldFromFinal, when the corresponding optional member exists. The ordinary ReturnFrom or YieldFrom remains the fallback.
Starting with F# 11, a final do! binds the operation and completes with unit instead of selecting a final-forwarding member. Normally it calls Bind then Return(()), or Zero() without Return. A Zero marked with DefaultValue takes precedence over Return. Binding optimizations such as BindReturn can still apply.
If your builder relied on the earlier behavior, supply binding and unit-completion methods. Use explicit return! or yield! only when you intend to forward the computation.
The distinction is observable in this builder:
type TraceBuilder() =
member _.Return(value) =
System.Console.WriteLine("Return")
value
member _.Zero() = ()
member _.Bind(value, continuation) =
System.Console.WriteLine("Bind")
continuation value
member _.ReturnFrom(value) =
System.Console.WriteLine("ReturnFrom")
value
member _.ReturnFromFinal(value) =
System.Console.WriteLine("ReturnFromFinal")
value
let trace = TraceBuilder()
let forwarded = trace { return! 42 }
let completed = trace { do! () }
The output is:
ReturnFromFinal
Bind
Return
A let! still requires a following body. For example, use async { let! value = work in return value }, not the incomplete async { let! value = work }.
To log an error and preserve its original exception identity and stack, use reraise () in a computation-expression with handler:
Note
This is an F# 11.2 feature. In the .NET 11.0.100 SDK, enable <LangVersion>preview</LangVersion>.
open System
open System.IO
open System.Threading.Tasks
let readReport (logFailure: exn -> Task) path =
task {
try
return! File.ReadAllTextAsync(path)
with :? IOException as error ->
do! logFailure error
return reraise ()
}
After the logger completes, reraise propagates the caught exception with its original throw-site information. If logging fails, its failure can replace the original. The nearest enclosing handler selects the exception; raise error doesn't preserve the stack in the same way.
Custom builders must infer the handler input as exn. The compiler uses ExceptionDispatchInfo, so dispatch frames can appear in the preserved stack.
Was this page helpful?