Alberto Ramón
Alberto Ramón

Reputation: 35

Variable Function: Sum elements of List

Why Line 1 and 2 works, but 3 fail ?¿:

val sum1= (a: Int, b: Int, c: Int) => a + b + c   //OK
List(1,2,3).reduceLeft(_+_)    //OK

val sum2 =(x: List) =>x.reduceLeft(_+_)    //Fail

Upvotes: 0

Views: 108

Answers (2)

flavian
flavian

Reputation: 28511

The compiler is missing proof that the underlying objects inside List are a type that defines the + operator. Here's a nice way to use the underlying Scala lib to define a method that is capable of adding a List of any numerical type.

For this, you don't even need reduce, as Scala already defines sum. List is a higher kinded type construcotr, more details here.

def addList[T : Numeric](list: List[T]): T = list.sum

Upvotes: 0

Clashsoft
Clashsoft

Reputation: 11882

You have to add the element type to x: List, so it becomes List[Int] or List[Double]. List itself is a raw type, which is illegal in Scala. Without the type annotation, the compiler also does not know what the + operator means in the reduceLeft(_+_) part, so it has to produce an error.

Upvotes: 1

Related Questions