简体   繁体   English

折叠中的三元运算符问题

[英]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;如果我用三元运算符(X?Y:Z)替换 if/else,它不起作用; 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.以同样的方式失败。

Scala doesn't have a ternary operator, because it has if which works as expression, so you can do things like: Scala 没有三元运算符,因为它有if可以用作表达式,因此您可以执行以下操作:

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)) }

Haha, sorry Guys!哈哈,对不起各位!

The simple solution is: There is no elvis operator in Scala.简单的解决办法是:Scala中没有elvis算子。 :) 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.与 Java 相比,Scala 从 if/else 语句返回一个值,因此您不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM