user unknown
user unknown

Reputation: 36229

Problem with the ternary operator in fold

Consider a simple Collection, searching the min and max in one iteration:

val v = Vector (2, 1, 3, 5, 4)
val mima = (v(0), v(0))
val mami = (mima /: v) {case ((a, b), c) => if (c<a) (c, b) else if (c>b) (a, c) else (a, b)}

So far, so straight forward. If I replace the if/else with the ternary operator (X ? Y : Z), it doesn't work; I get an error:

    val mami = (mima /: v) {case ((a, b), c) => (c<a) ? (c, b) : (c>b) ? (a, c) : (a, b)}
<console>:1: ';' expected but : found. 

at the last colon. Adding parens didn't help:

    val mami = (mima /: v) {case ((a, b), c) => (c<a) ? (c, b) : ((c>b) ? (a, c) : (a, b))}

Do I make a silly mistake or is there is a subtle problem with the nested ternary operator?

Hunting this problem down, it isn't related to folds, only:

if (c < 4) "small" else if (c > 8) "big" else "medium"

works

(c < 4) ? "small" : (c > 8) ? "big" : "medium" 

fails the same way.

Upvotes: 2

Views: 240

Answers (2)

user unknown
user unknown

Reputation: 36229

Haha, sorry Guys!

The simple solution is: There is no elvis operator in Scala. :) Gee, how could I forget that?

(a < 4) ? foo : bar 

isn't that much shorter than

if (a < 4) foo; else bar

and in contrast to Java, Scala returns a value from an if/else statement, hence you don't need it.

Upvotes: 1

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

Scala doesn't have a ternary operator, because it has if which works as expression, so you can do things like:

val result = if (c < 4) "small" else if (c > 8) "big" else "medium"

You can also use it in fold:

val mami = (mima /: v) {case ((a, b), c) => if (c<a) (c, b) else if (c>b) (a, c) else (a, b)) }

Upvotes: 5

Related Questions