forki23
forki23

Reputation: 2814

Defining new keywords in F#'s computation expression

The F# 3.0 beta contains a query {} computation expression with tons of new keywords.

How can I define my own keywords in a computation builder?

Upvotes: 21

Views: 3425

Answers (2)

shr
shr

Reputation: 1035

F# computation expressions support custom keywords. This lets you define custom commands inside computation expression. Saturn - the web framework in F# uses this extensively.

type FooBuilder() =
    member t.Yield _ = String.Empty

    [<CustomOperation("fooCommand")>]
    member _.myFooCommand(state, arg1:string, arg2:string) =
        // do something with arg1 and arg2
        0

    [<CustomOperation("fooRun")>]
    member _.myFooRunMethod(state, arg1: float) =
        // do something with arg1 
        0
            

let foo = FooBuilder()
let _ = foo {
        fooCommand "dotnet" "--help"
        fooRun 3.14
}

You can thread a 'state' through the calls. Read more about it in the article by Isaac Abraham on this topic -- https://www.compositional-it.com/news-blog/custom-keywords-in-computation-expressions/

Saturn code -- https://github.com/SaturnFramework/Saturn

Upvotes: 0

pad
pad

Reputation: 41290

In F# 3.0, you can use CustomOperationAttribute for this purpose.

The new attribute is not very well-documented, the only examples I find are this great answer by @Tomas and this interesting blog post.

Upvotes: 24

Related Questions