将Scala循环简化为一行

时间:2017-01-25 18:55:24

标签: scala

如何使用Scala将此循环简化为某些函数(如foreach或map或其他内容)?我想将hitsArray放在过滤器shipList.filter中。

val hitsArray: Array[String] = T.split(" ");
for (hit <- hitsArray) {
  shipSize = shipList.length
  shipList = shipList.filter(!_.equalsIgnoreCase(hit))
}
if (shipList.length == 0) {
  shipSunk = shipSunk + 1
} else if (shipList.length < shipSize) {
  shipHit = shipHit + 1
}

2 个答案:

答案 0 :(得分:2)

公平地说,我不明白为什么你打电话给shipSize = shipList.length,因为你不在任何地方使用它。

T.split(" ").foreach{ hit => 
  shipList = shipList.filter(!_.equalsIgnoreCase(hit)) 
}

让你到达你想去的地方。我已经做了3行,因为你想强调你在foreach中通过副作用来工作。也就是说,我认为没有任何优势可以使它成为单线。你之前所拥有的是完全可读的。

答案 1 :(得分:2)

这样的事可能吗?

shipList.filter(ship => T.split(" ").forall(!_.equalsIgnoreCase(ship)))

虽然shipList已全部为小写,但更清晰:

shipList.filterNot(T.split(" ").map(_.toLowerCase) contains _)

或者,如果您的T很大,请将其移出循环:

val hits = T.split(" ").map(_.toLowerCase)
shipList.filterNot(hits contains _)