Computing in Scala, what types will compile these statements?

So, I have this function in Scala:

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

Question: What are the three types that the following operators 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 don't quite understand the concept of currying. Maybe an answer to this question with some explanation will really help me. Thanks.

+6
source share
2 answers

First, one main thing: a function that takes two parameters aand band returns a value ccan be considered as a function that takes aand returns a function that takes band returns c. This “change of perspective” is called currying.

, . 2 3, 5. , . 2, , 2 .

, , :

// 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 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 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 type
+7

Currying IMO - Scala. , wikipedia,

, ( ) , .

, f(a, b, c) f(a)(b)(c). Scala? . , . f ( Scala ) Int => (Int => (Double => (Double => Double))). f:

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

, . . , . , . :

scala> f(0)
<console>:01: error: missing argument list for method f
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `f _` or `f(_)(_)(_)(_)` instead of `f`.

, , : f(0) Scala eta-, , :

scala> val fl: (Int => (Double => (Double => Double))) = f(0)
fl: Int => (Double => (Double => Double)) = $$Lambda$1342/937956960@43c1614

eta- :

scala> val fl: (Int => (Double => (Double => Double))) = (b => (c => (d => f(0)(b)(c)(d))))
fl: Int => (Double => (Double => Double)) = $$Lambda$1353/799716194@52048150

() curries - placeholder ( ):

scala> f _
res11: Int => (Int => (Double => (Double => Double))) = $$Lambda$1354/1675405592@4fa649d8

scala> f(0) _
res12: Int => (Double => (Double => Double)) = $$Lambda$1355/1947050122@ba9f744

, :

def g: Int => (Double => (Double => Double)) = f(0)

def g: Int => (Double => (Double => Double)) = (b => (c => (d => f(0)(b)(c)(d))))

. g, " " . , g(0) " g , 0".

0

All Articles