Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currying Example in Scala

Tags:

scala

currying

Is the following a good example of currying?

def sum(a: Int, b: Int) : (Int => Int) = {
    def go(a: Int) : Int = {
        a + b;
    }
    go
}

I half understand the below results, but how could I write (or maybe how I should've written) sum() in a curried way?

scala> sum(3,4) res0: Int => Int = <function1>
scala> sum(3,4).apply(2) res1: Int = 6
scala> sum(3,4).apply(3) res2: Int = 7
like image 209
Kevin Meredith Avatar asked Dec 11 '22 13:12

Kevin Meredith


1 Answers

Currying mechanism was introduced in Scala to support type inference. For example foldLeft function in the standard lib:

def foldLeft[B](z: B)(op: (B, A) => B): B

Without currying you must provide types explicitly:

def foldLeft[B](z: B, op: (B, A) => B): B
List("").foldLeft(0, (b: Int, a: String) => a + b.length)
List("").foldLeft[Int](0, _ + _.length)

There are three ways to write a curried function:

1) Write it in currying form:

def sum(a: Int)(b: Int) = a + b

which is just syntactic sugar for:

def sum(a: Int): Int => Int = b => a + b

2) Call curried on the function object (sum _).curried and check the types:

sum: (a: Int, b: Int)Int
res10: Int => (Int => Int) = <function1>

In your example, you can use Scala type inference to reduce the amount of code and change your code:

def sum(a: Int, b: Int) : (Int => Int) = {
    def go(a: Int) : Int = {
        a + b;
    }
    go
}

into:

def sum(a: Int, b: Int) : (Int => Int) = c => a + b + c

semantically these are the same, because you explicitly provided the return type, so Scala knows that you will return a function wich takes an Int argument and return an Int

Also a more complete answer about curring was given by retronym

like image 68
4lex1v Avatar answered Jan 02 '23 18:01

4lex1v