I am new to scala , I have written same code in 2 ways . But i am bit confused between 2 ways. In Second way argument type of f are derived automatically but in type1 scala compiler is not able to do the same . I just want to understand what is the thought behind this .
Type1: Gives compilation error
def rightFold[A,B](xs:List[A],z:B,f:(A,B) => B ): B = xs match {
case Nil => z
case Cons(x,xs) => f(x,rightFold(xs,z,f))
}
def sum1(l:List[Int]) = rightFold(l,0.0,_ + _)
Type2 : Works fine
def rightFold[A,B](xs:List[A],z:B)(f:(A,B) => B ): B = xs match {
case Nil => z
case Cons(x,xs) => f(x,rightFold(xs,z)(f))
}
def sum1(l:List[Int]) = rightFold(l,0.0)(_ + _)
Type inference flows from left-to-right through argument lists. In other words, type information from left argument lists is available in right argument lists, but argument types within the same list are inferred independently.
This is not about function types need to be passed in a separate group of arguments (currying).The problem is with your usage of + on types that the Scala doesn't know about yet.
When you curry a function, the compiler is able to infer the type of the first two arguments as being List[Int] and Double already. This allows the + to be resolved as it knows that the types are Int and Dobule on the two sides.
Now why can't the compiler do the same with the single arguments list - that's just how it is, type information is not available within an argument list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With