为什么这个计算表达式生成器期望在我的 for 循环中"unit"?



这是此问题的后续问题。

我正在尝试创建一个计算表达式生成器,该生成器通过自定义操作累积值,同时还支持标准F#语言构造。为了有一个简单的例子,我使用了一个构建F#列表的计算表达式。感谢kvb和Daniel的建议,我走得更远了,但for循环仍然有问题。

建设者:

type Items<'a> = Items of 'a list
type ListBuilder() =
    member x.Yield(vars) = Items [], vars
    member x.Run(l,_) = l
    member x.Zero() = Items [], ()
    member x.Delay f = f()
    member x.ReturnFrom f = f
    member x.Combine((Items curLeft, _), (Items curRight, vars)) =
        (Items (curLeft @ curRight), vars)
    member x.Bind(m: Items<'a> * 'v, f: 'v -> Items<'a> * 'o) : Items<'a> * 'o =
        let (Items current, vals) = m
        x.Combine(m, f vals)
    member x.While(guard, body) =
        if not (guard()) then
            x.Zero()
        else
            x.Bind(body, fun () -> x.While(guard, body))
    member x.TryWith(body, handler) =
        try
            x.ReturnFrom(body())
        with e ->
            handler e
    member x.TryFinally(body, compensation) =
        try
            x.ReturnFrom(body())
        finally
            compensation()
    member x.Using(disposable:#System.IDisposable, body) =
        let body' = fun() -> body disposable
        x.TryFinally(body', fun () ->
            match disposable with
            | null -> ()
            | disp -> disp.Dispose())
    member x.For(xs:seq<'a>, body) =
        x.Using(xs.GetEnumerator(), fun enum ->
            x.While(enum.MoveNext, x.Delay(fun () -> body enum.Current)))
    [<CustomOperation("add", MaintainsVariableSpace=true)>]
    member x.Add((Items current, vars), [<ProjectionParameter>] f) =
        Items (current @ [f vars]), vars
    [<CustomOperation("addMany", MaintainsVariableSpace=true)>]
    member x.AddMany((Items current, vars), [<ProjectionParameter>] f) =
        Items (current @ f vars), vars

let listBuilder = ListBuilder()
let build (Items items) = items

这个版本允许我以前做不到的事情,比如:

let stuff = 
    listBuilder {
        let x = 5 * 47
        printfn "hey"
        add x
        addMany [x .. x + 10]
    } |> build

然而,我仍然在这个问题上遇到编译器错误:

let stuff2 =
    listBuilder {
        for x in 1 .. 50 do
            add x            
    } |> build

在这种情况下,IDE在for x in中的x下面划线,并告诉我,"这个表达式应该有类型unit,但这里有类型int。"

我并不清楚为什么它期望循环变量的类型为unit。很明显,我在某个地方得到了错误的方法签名,我怀疑我没有在应该的每个地方传递我的累积状态,但编译器错误并不能帮助我缩小错误的范围。如有任何建议,我们将不胜感激。

直接原因是While函数约束了body的类型。然而,通常情况下,您不能在同一计算表达式中同时使用自定义操作和控制流运算符,因此我认为即使修复了签名,也无法完全执行您想要的操作。

相关内容

  • 没有找到相关文章

最新更新