如何编写递归匿名函数? [英] How do I write recursive anonymous functions?
问题描述
在我继续努力学习 Scala 的过程中,我正在学习 Odersky 的Scala by example"和关于一等函数的章节,匿名函数部分避免了递归匿名函数的情况.我有一个似乎有效的解决方案.我很好奇是否有更好的答案.
In my continued effort to learn scala, I'm working through 'Scala by example' by Odersky and on the chapter on first class functions, the section on anonymous function avoids a situation of recursive anonymous function. I have a solution that seems to work. I'm curious if there is a better answer out there.
来自pdf:展示高阶函数的代码
From the pdf: Code to showcase higher order functions
def sum(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sum(f, a + 1, b)
def id(x: Int): Int = x
def square(x: Int): Int = x * x
def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x-1)
def sumInts(a: Int, b: Int): Int = sum(id, a, b)
def sumSquares(a: Int, b: Int): Int = sum(square, a, b)
def sumPowersOfTwo(a: Int, b: Int): Int = sum(powerOfTwo, a, b)
scala> sumPowersOfTwo(2,3)
res0: Int = 12
来自pdf:展示匿名函数的代码
from the pdf: Code to showcase anonymous functions
def sum(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sum(f, a + 1, b)
def sumInts(a: Int, b: Int): Int = sum((x: Int) => x, a, b)
def sumSquares(a: Int, b: Int): Int = sum((x: Int) => x * x, a, b)
// no sumPowersOfTwo
我的代码:
def sumPowersOfTwo(a: Int, b: Int): Int = sum((x: Int) => {
def f(y:Int):Int = if (y==0) 1 else 2 * f(y-1); f(x) }, a, b)
scala> sumPowersOfTwo(2,3)
res0: Int = 12
推荐答案
对于它的价值...(标题和真正的问题"不太一致)
For what it's worth... (the title and "real question" don't quite agree)
递归匿名函数对象可以通过FunctionN
的长手"扩展然后使用this(...)
创建apply
里面.
(new Function1[Int,Unit] {
def apply(x: Int) {
println("" + x)
if (x > 1) this(x - 1)
}
})(10)
然而,这通常引入的讨厌程度使得该方法通常不太理想.最好只使用一个名称"并有一些更具描述性的模块化代码——并不是说以下是这种情况的一个很好的论据;-)
However, the amount of icky-ness this generally introduces makes the approach generally less than ideal. Best just use a "name" and have some more descriptive, modular code -- not that the following is a very good argument for such ;-)
val printingCounter: (Int) => Unit = (x: Int) => {
println("" + x)
if (x > 1) printingCounter(x - 1)
}
printingCounter(10)
快乐编码.
这篇关于如何编写递归匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!