Scala 中的匿名递归函数 [英] Anonymous recursive function in Scala
本文介绍了Scala 中的匿名递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Scala 中编写一个递归的匿名函数?我在想这样的事情:
Is there a way to write an anonymous function that is recursive in Scala? I'm thinking of something like this:
((t: Tree) => {
print(t.value);
for (c <- t.children)
thisMethod(c)
})(root)
(相关问题:哪些语言支持*递归*函数字面量/匿名函数?)
推荐答案
如您发布的链接中所述.您可以使用 Y 组合器.示例如下:
As described in the link you posted. You can use Y-combinator. Here is example:
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
请注意,它不适用于大数字.小心尾调用优化.
Note it doesn't work with big numbers. Be careful with tail call optimization.
这篇关于Scala 中的匿名递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文