Nul*_*lle 5 recursion f# member-functions
我理解当你在一个类型中定义一个递归成员函数时,就没有必要将函数定义为递归.意思是使用rec关键字.
但是当我这样做时:
type hello() = class
member this.recursion(x) =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
recursion(x+1)
end
Run Code Online (Sandbox Code Playgroud)
然后我得到没有定义递归的错误.
我试过this.recursion但是我仍然得到一个警告说:
递归对象引用'this'未使用.递归对象引用的存在将运行时初始化检查添加到此类和派生类型中的成员.考虑删除此递归对象引用.
所以我想知道在一个类型中定义递归成员函数的正确方法是什么?
Gus*_*Gus 11
是的,它们在被定义为成员时起作用.正如您已经注意到的那样,您错过this了呼叫站点.它应该是:
this.recursion(x+1)
Run Code Online (Sandbox Code Playgroud)
但这很有效,至少对我而言:
type hello() = class
member this.recursion(x) =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
this.recursion(x+1)
end
Run Code Online (Sandbox Code Playgroud)
无论如何,我会在内部定义它,如在另一个答案中所示,但在方法内:
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
Run Code Online (Sandbox Code Playgroud)