代码之家  ›  专栏  ›  技术社区  ›  blue-sky

如何调用接受函数参数的函数?

  •  1
  • blue-sky  · 技术社区  · 11 年前

    观看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 回复  |  直到 11 年前
        1
  •  2
  •   faissalb    11 年前

    调用简单如下:

    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))
    
    推荐文章