有没有办法在 Scala 中编写递归的匿名函数?我正在考虑这样的事情:
((t: Tree) => {
print(t.value);
for (c <- t.children)
thisMethod(c)
})(root)
(相关问题:Which languages support *recursive* function literals / anonymous functions?)
最佳答案
如您发布的链接中所述。您可以使用 Y 组合器。这是示例:
scala> def fix[A,B](f: (A=>B)=>(A=>B)): A=>B = f(fix(f))(_)
fix: [A,B](f: ((A) => B) => (A) => B)(A) => B
scala> val fact = fix[Int,Int](f => a => if(a<=0) 1 else f(a-1) * a)
fact: (Int) => Int = <function1>
scala> fact(12)
res0: Int = 479001600
请注意,它不适用于大数字。 小心尾部调用优化。
关于scala - Scala 中的匿名递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5337464/