如何调用带函数参数的函数?

时间:2014-08-16 09:50:05

标签: scala sicp

观看SICP课程https://www.youtube.com/watch?v=erHp3r6PbJk&index=3&list=PLB63C06FAF154F047我已将一些lisp代码转换为Scala:

def sumInt(a: Int, b: Int): Int = {     //> sumInt: (a: Int, b: Int)Int
  if(a > b) 0
  else a + sumInt(1 + a, b)
}                                               

sumInt(3, 5)                            //> res0: Int = 12

def sumSquares(a: Int, b: Int): Int = { //> sumSquares: (a: Int, b: Int)Int
  if(a > b) 0
  else (a * a) + sumSquares(1 + a, b)
}                                               

sumSquares(2, 3)                        //> res1: Int = 13

要创建一个更通用的函数,它接受函数作为参数来计算正方形,而不是在我添加的函数中对它们进行编码:

def sum(term: Int => Int, a: Int, next: Int => Int, b: Int): Int = {
  if(a > b) 0
  else {
    val toAdd1 = term(a)
    val toAdd2 = toAdd1 + sum(term, next(a), next, b)
    toAdd1 + toAdd2
  }
}   

但我不确定如何调用此功能?这可以更通用,以便参数a& b不必是Int类型的?

1 个答案:

答案 0 :(得分:2)

调用就像执行:

一样简单
println(sum({x=>x},1,{x=>x+1},4))

有关编写此函数的更通用的原因,您可以使用scala Numeric:

def sumG[A](term: A => A, a: A, next: A => A, b: A)(implicit n: Numeric[A]): A = {
  if(n.compare(a,b)>0) 
      n.zero
  else
     n.plus(term(a),sumG(term, next(a), next, b))
}

这称之为:

println(sumG[Int]({x=>x},1,{x=>x+1},4))