Defining new keywords in F#'s computation expression
Asked Answered
C

2

21

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?

Crist answered 5/3, 2012 at 11:39 Comment(0)
H
24

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.

Heyde answered 5/3, 2012 at 11:53 Comment(0)
E
0

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

Expectorate answered 9/1 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.