如何编写递归匿名函数? [英] How do I write recursive anonymous functions?

查看:141
本文介绍了如何编写递归匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我继续学习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 的长手"扩展来创建递归匿名函数对象,然后在apply中使用this(...).

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆