Priyaranjan Swain
Priyaranjan Swain

Reputation: 361

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)(_ + _)

Upvotes: 3

Views: 98

Answers (4)

user1303559
user1303559

Reputation: 436

With single list an inferred type of A depends on the types of xs and f. But with the two lists of arguments it depends just on the xs type.

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

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.

Upvotes: 4

Ophirr33
Ophirr33

Reputation: 185

Type 1 would work if instead of passing in _ + _ you pass in (a: Int, b: Double) => (a + b)). Currying the function lets you use the underline syntax, because the scala compiler has inferred what types A and B are by the time you try and pass in the addition function.

Upvotes: 3

manojlds
manojlds

Reputation: 301147

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.

Upvotes: 3

Related Questions