如何使用CustomOperations实现Stateful Builder,并使用一些let

时间:2017-06-14 08:48:38

标签: f# computation-expression

我正试图定义一个有状态的构建器并且我无法解决一些编译器错误

type Movement =
    | Left of int
    | Right of int

type MovementState = Movement list -> Movement list

type MovementBuilder () =
    member x.Zero () : MovementState = id
    member __.Return x : MovementState = id
    member __.Bind(m: MovementState, f: MovementState ) = fun v -> f (m v)

    [<CustomOperation("left", MaintainsVariableSpaceUsingBind = true)>]
    member x.Left(ms, value) = x.Bind(ms, fun xs -> xs @ [Left value])

    [<CustomOperation("right", MaintainsVariableSpaceUsingBind = true)>]
    member x.Right(ms, value) = x.Bind(ms, fun xs -> xs @ [Right value])

let movement = MovementBuilder()

[]
|> movement {
    left 10
    right 20
}
|> printfn "list %A"
//prints [Left 10; Right 20]

但是现在我要介绍一个let!yield,这样我就可以添加其他项目而无需通过定义的CustomOperations 所以我可以这样以下

[]
|> movement {
    left 10
    let! _ = (fun xs -> xs @ [Right 99])
    //I also tried naming the value
    //let! x = (fun xs -> xs @ [Right 99])
    //I also tried wrapping it into another function ...
    //let! x = fun () -> (fun xs -> xs @ [Right 99])
    right 20
}
|> printfn "list %A"
//Should print [Left 10; Right 99; Right 20]

非常感谢任何帮助。 Bonus Karma将被发送以解释编译器如何将其重写为一系列Bind s

THX

1 个答案:

答案 0 :(得分:3)

你似乎在这里有一个monadic类型,它不能包含&#34;任何事情(即Async&lt;&#39; a&gt;都可以包含&#39; a)。

这意味着唯一能够绑定的合理类型是unit,它会生成绑定member __.Bind(m: MovementState, f : unit -> MovementState)的签名。

这允许您使用do!表示法来操作您的移动状态列表,并且意味着对您的左右方法进行一些重写。我相信你的构建器也需要一个combine方法,但编译器会告诉你你是否快速完成! let!符号在这里没有多大意义,因为你没有&#34;包含&#34;输入要打开的类型。

我在blog post中有一个简短的例子,下面是最相关的代码:

type PTD = ProvidedTypeDefinition -> ProvidedTypeDefinition

type ProvidedTypeBuilder () =
    member __.Zero () : PTD =
        id
    member __.Return _ : PTD =
        id
    member __.Bind(m, f : unit -> PTD) =
        fun ptd -> (f ()) (m ptd)
    member x.Combine(m1 : PTD, m2 : PTD) : PTD =
        x.Bind(m1, fun () -> m2)

    [<CustomOperation("addMember", MaintainsVariableSpaceUsingBind = true)>]
    member x.AddMember(ptd, member') =
        let func =
          fun (instance : ProvidedTypeDefinition) ->
              instance.AddMember member'
              instance
        x.Bind(ptd, fun () -> func)

作为如何使用do!表示法的示例,您可以执行以下操作而不是构建自定义操作:

let ptd = ProvidedTypeBuilder()

let test =
    ptd {
        addMember (ProvidedProperty("MyProp", typeof<string>))
        do! (fun ptd -> ptd.AddObsoleteAttribute("Hey, don't use this anymore"); ptd)
    }