Aracılığıyla paylaş


Computation Expressions (F#)

Computation expressions in F# provide a convenient syntax for writing computations that can be sequenced and combined using control flow constructs and bindings. They can be used to provide a convenient syntax for monads, a functional programming feature that can be used to manage data, control, and side effects in functional programs.

Built-in Workflows

Sequence expressions are an example of a computation expression, as are asynchronous workflows. For more information about sequence expressions, see Sequences. For more information about asynchronous workflows, see Asynchronous Workflows.

Certain features are common to both sequence expressions and asynchronous workflows and illustrate the basic syntax for a computation expression:

builder-name { expression }

The previous syntax specifies that the given expression is a computation expression of a type specified by builder-name. The computation expression can be a built-in workflow, such as seq or async, or it can be something you define. The builder-name is the identifier for an instance of a special type known as the builder type. The builder type is a class type that defines special methods that govern the way the fragments of the computation expression are combined, that is, code that controls how the expression executes. 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.

In computation expressions, two forms are available for some common language constructs. You can invoke the variant constructs by using a ! (bang) suffix on certain keywords, such as let!, do!, and so on. These special forms cause certain functions defined in the builder class to replace the ordinary built-in behavior of these operations. These forms resemble the yield! form of the yield keyword that is used in sequence expressions. For more information, see Sequences.

Creating a New Type of Computation Expression

You can define the characteristics of your own computation expressions by creating a builder class and defining certain special methods on the class. The builder class can optionally define the methods as listed in the following table.

The following table describes methods that can be used in a workflow builder class.

Method

Typical signature(s)

Description

Bind

M<'T> * ('T -> M<'U>) -> M<'U>

Called for let! and do! in computation expressions.

Delay

(unit -> M<'T>) -> M<'T>

Wraps a computation expression as a function.

Return

'T -> M<'T>

Called for return in computation expressions.

ReturnFrom

M<'T> -> M<'T>

Called for return! in computation expressions.

Run

M<'T> -> M<'T> or

M<'T> -> 'T

Executes a computation expression.

Combine

M<'T> * M<'T> -> M<'T> or

M<unit> * M<'T> -> M<'T>

Called for sequencing in computation expressions.

For

seq<'T> * ('T -> M<'U>) -> M<'U>

Called for for...do expressions in computation expressions.

TryFinally

M<'T> * (unit -> unit) -> M<'T>

Called for try...finally expressions in computation expressions.

TryWith

M<'T> * (exn -> M<'T>) -> M<'T>

Called for try...with expressions in computation expressions.

Using

'T * ('T -> M<'U>) -> M<'U> when 'U :> IDisposable

Called for use bindings in computation expressions.

While

(unit -> bool) * M<'T> -> M<'T>

Called for while...do expressions in computation expressions.

YieldFrom

M<'T> -> M<'T>

Called for yield! expressions in computation expressions.

Zero

unit -> M<'T>

Called for empty else branches of if...then expressions in computation expressions.

Many of the methods in a workflow 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 asynchronous workflows 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. The compiler, when it parses a computation expression, converts 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 calls involving the methods of the builder class by the translations described in the following table. The computation expression {| cexpr |} is defined recursively according to these translations where expr is an F# expression and cexpr is 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(expr1, (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 binder.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 expr do cexpr |}

builder.For(enumeration, (fun pattern -> {| cexpr }|))

{| for identifier = expr1 to expr2 do cexpr |}

builder.For(enumeration, (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 -> reraise exn)))

{| 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 illustrates the creation and use of a simple computation expression type that generates some console output that tracks the progress of the execution of code.

// Program.fs
open Module1

// Create the computation expression object.
let trace1 = trace {
   // A normal let expression (does not call Bind).
   let x = 1
   // A let expression that uses the Bind method.
   let! y = 2
   let sum = x + y
   // return executes the Return method.
   return sum  
   }

// Execute the code. Start with the Delay method.
let result = trace1()

The following code implements the builder class for the trace computation expression.

// Module1.fs
module Module1 =

 // Functions that implement the builder methods.
 let bind value1 function1 = 
     printfn "Binding %A." value1 
     function1 value1

 let result value1 =
     printfn "Returning result: %A" value1
     fun () -> value1

 let delay function1 =
     fun () -> function1()

 // The builder class for the "trace" workflow.
 type TraceBuilder() =
     member x.Bind(value1, function1) = 
         bind value1 function1
     member x.Return(value1)  = result value1
     member x.Delay(function1)   = 
         printfn "Starting traced execution."
         delay function1

 let trace = new TraceBuilder()

The output of this example is as follows.

Starting traced execution.
Binding 2.
Returning result: 3

See Also

Other Resources

F# Language Reference

Change History

Date

History

Reason

December 2010

Added Run method and table of translations.

Customer feedback.