Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currying in Scala, what are the types that make these statements compile?

Tags:

scala

So I have this function in Scala:

def f(a: Int)(b: Int)(c: Double)(d: Double): Double = a * c + b * d

The question is What are the three types that make the following statements compile.

def g: <Type1> = f(1)(2)(3.0) 
def h: <Type2> = f(1)(2) 
def k: <Type3> = f(1)

I'm still new to Scala and I am not really understanding the concept of currying. Maybe an answer to this question with some explanation will really help me. Thanks.

like image 658
saydak Avatar asked Mar 05 '18 16:03

saydak


1 Answers

First, one main thing: function that takes two parameters a and b and returns a value c can be viewed as a function that takes an a and returns a function that takes b and returns c. This "change of point of view" is called currying.

Imagine a function that sums up two numbers. You give it 2 and 3, it returns 5. It can be viewed as a function that takes one number and returns a function from a number to a number. You give it a 2, it returns a function that takes some number and adds 2 to it.

Now, some types that you requested:

// pseudocode!

def g: Double => Double 
  = f(1)(2)(3.0) // we supply three params and are left with only one, "d"
  = (d: Double) => 1 * 3.0 + 2 * d // we comply with g's type

def h: Double => Double => Double // or (Double, Double) => Double 
  = f(1)(2) // we supply two params and are left with two more, "c" and "d"
  = (c: Double)(d: Double) => 1 * c + 2 * d // we comply with h's type

def k: Double => Double => Double => Double // or (Double, Double, Double) => Double
  = f(1) // we supply one param and are left with three more, "b", "c" and "d"
  = (b: Double)(c: Double)(d: Double) => 1 * c + b * d // we comply with k's type
like image 57
slouc Avatar answered Oct 25 '22 07:10

slouc