Abhi
Abhi

Reputation: 6568

Invoking higher order functions - Scala

Hi I am new to Scala and trying to call a higher order function sum_of from main class.I am getting "Cannot resolve reference sumOf with such signature error".

object SumOf {

  def main(args: Array[String]) {
   val y =  sumOf(x=>x ,4,5)
    println(y)
  }

  def sumOf(f: Int => Int)(a: Int, b: Int): Int = {
    def loop(a: Int, acc: Int): Int =
      if (a > b) acc
      else loop(a + 1, f(a) + acc)
      loop(a, 0)
    }

}

Upvotes: 0

Views: 132

Answers (2)

Brian
Brian

Reputation: 20285

sumOf is a curried function so it takes two arguments in the form of sumOf(x => x)(4,5) which is different from sumOf(x => x, 4,5). This is the reason you are getting an error.

Further, you can call it with only one argument sumOf(x => x) _ which returns another function that takes the second argument (Int, Int) => Int = <function2> and return a function. This is more commonly known as partial function application.

Upvotes: 2

Dylan
Dylan

Reputation: 13914

Your sumOf method has two argument lists, and needs to be called with two argument lists.

val y = sumOf(x => x)(4, 5)

You can think of sumOf as a function which takes an Int => Int and returns a new function, which takes two Ints to return an Int.

Upvotes: 1

Related Questions