我正在努力定义一个有状态的构建器,但我无法解决一些编译器错误
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
谢谢