Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why in Scala a function type needs to be passed in separate group of arguments into a function

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)(_ + _)
like image 444
Priyaranjan Swain Avatar asked Dec 28 '25 00:12

Priyaranjan Swain


2 Answers

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.

like image 98
Jörg W Mittag Avatar answered Dec 30 '25 23:12

Jörg W Mittag


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.

like image 44
manojlds Avatar answered Dec 31 '25 00:12

manojlds