hawarden_
hawarden_

Reputation: 2160

Scala: function declaration when doing currying

I am learning Scala and I don't quite understand:

  1. why the code sum1 can't be rewritten by sum2?

  2. why in sum1, a and b automatically know (Int,Int) correspond to a and b?

Thanks in advance.

    def sum1 (f: Int => Int) : (Int, Int) => Int = {
      def sumF(a:Int, b:Int) : Int = {
        if (a > b) 0
      else f(a) + sumF(a + 1, b)
      }
      sumF
    }

    def sum2 (f: Int => Int, Int, Int) : Int = {
      def sumF(a:Int, b:Int) : Int = {
        if (a > b) 0
        else f(a) + sumF(a + 1, b)
      }
      sumF
    }

Upvotes: 1

Views: 51

Answers (1)

Aleksey Isachenkov
Aleksey Isachenkov

Reputation: 1240

  1. It's because sum1 and sum2 have different interfaces: sum1 is (Int => Int) => ((Int, Int) => Int) and sum2 is (Int => Int, Int, Int) => Int. I.e. sum1 returns function that accepts two integers and returns an integer. But sum2 returns just an integer value, not a function.

  2. Your sumF function equal to a lambda function

    val sumF: (Int, Int) => Int = (a: Int, b: Int) => {
        if (a > b)
            0
        else
            f(a) + sumF(a + 1, b)
    }
    

    You can see it if you try to save sumF into value (it would look like val tmp: (Int, Int) => Int = sumF)

Upvotes: 3

Related Questions