我的理解是,当您在类型中定义递归成员函数时,则无需将函数定义为递归。含义rec
关键字。
但是,当我这样做时:
type hello() = class
member this.recursion(x) =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
recursion(x+1)
end
然后我得到递归未定义的错误。
我已经尝试过
this.recursion
,但是随后我仍然收到警告说:递归对象引用“this”未使用。递归对象引用的存在将运行时初始化检查添加到此类型和派生类型的成员中。考虑删除此递归对象引用。
所以我想知道在类型中定义递归成员函数的正确方法是什么?
最佳答案
是的,它们在定义为成员时起作用。
正如您已经注意到的,您在调用站点上缺少this
。它应该是:
this.recursion(x+1)
但这很好,至少对我而言:
type hello() = class
member this.recursion(x) =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
this.recursion(x+1)
end
无论如何,我会在内部定义它,如其他答案所示,但在方法内部:
type hello() = class
member this.recursion(x) =
let rec loop x =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
loop (x+1)
loop x
end
关于recursion - F#递归成员函数: "How to Define it correctly",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764356/