astay13
astay13

Reputation: 6927

Plus not working in Scala interpreter

I am trying to sum a list using fold in the Scala interpreter, but it keeps giving me a strange error. When I type this:

val list = List(1,2,3)
(list :\ 0)(+)

I expect to get 6. However, the interpreter says

error: illegal start of simple expression
(list :\ 0)(+)
             ^

If I define my own function

def plus(a: Int, b: Int) = a+b

and call

(list :\ 0)(plus)

I do in fact get 6.

I'm sure I'm missing something really simple here, but I can't figure it out, so any help is much appreciated.

Upvotes: 3

Views: 325

Answers (2)

Neil Essy
Neil Essy

Reputation: 3607

The plus operator by itself is not a function it is a symbol and has no type. What you are looking for is the following

val list = List(1,2,3)
(list :\ 0)(_+_)

The _+_ is shorthand for an anonymous function that takes two parameters and calls the + method on the first parameter passing in the second.

Upvotes: 10

Aaron
Aaron

Reputation: 2185

Try this:

(list :\ 0)(_ + _)

You need to use the wildcards to show the Scala compiler that you want to call the "+" method on first of the arguments instead of using the Tuple2 as an argument to a function itself.

Upvotes: 3

Related Questions