如何编写递归匿名函数?

| 在继续学习scala的过程中,我正在研究Odersky的“ Scala by example”,以及有关一流函数的章节中,有关匿名函数的部分避免了递归匿名函数的情况。我有一个可行的解决方案。我很好奇是否有更好的答案。 从pdf: 展示高阶功能的代码
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: 展示匿名功能的代码
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
    
已邀请:
        为了它的价值...(标题和“实际问题”不太同意) 递归匿名函数对象可以通过扩展“ 3”的“长手”来创建,然后在5内使用4来创建。
(new Function1[Int,Unit] {
  def apply(x: Int) {
    println(\"\" + x)
    if (x > 1) this(x - 1)
  }
})(10)
但是,这种方法通常会引入大量的臭味,因此通常使该方法不理想。最好只使用\“ name \”并具有一些更具描述性的模块化代码-并不是说以下是此类的很好的论点;-)
val printingCounter: (Int) => Unit = (x: Int) => {
    println(\"\" + x)
    if (x > 1) printingCounter(x - 1)
}
printingCounter(10)
快乐的编码。     
        您可以将此间接递归概括为:
case class Rec[I, O](fn : (I => O, I) => O) extends (I => O) {
  def apply(v : I) = fn(this, v)
}
现在可以使用间接递归将sum编写为:
val sum = Rec[Int, Int]((f, v) => if (v == 0) 0 else v + f(v - 1))
例如,相同的解决方案可用于实现备忘录。     

要回复问题请先登录注册