如何使用自定义操作和一些让实现有状态生成器



我试图定义一个有状态的构建器,但我无法绕过一些编译器错误

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,这样我就可以添加其他项目,而无需通过定义的自定义操作这样,例如我可以这样

[]
|> 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]

任何帮助将不胜感激。将发送奖励业力,以解释编译器如何将其重写为一系列Bind

感谢

你似乎有一个不能"包含"任何东西的monadic类型(即Async<'a>可以包含'a'的类型(。

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

这允许您使用do!表示法来操作移动状态列表,并且意味着对左右方法进行一些重写。我相信你的构建器上也需要一个组合方法,但编译器会很快让你知道你是否这样做! let!符号在这里没有多大意义,因为您没有要解开包装的"包含"类型。

我在一篇博客文章中有一个简短的例子,下面最相关的代码:

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)
    }

相关内容

  • 没有找到相关文章