【发布时间】:2017-09-17 02:51:39
【问题描述】:
什么是过滤元组列表的好方法(阅读更好的可读性)。我正在使用
tupleList.filter(_._2).map(_._1)
但这感觉不可读。
【问题讨论】:
-
能否提供样本数据?
标签: scala filter functional-programming scala-collections readability
什么是过滤元组列表的好方法(阅读更好的可读性)。我正在使用
tupleList.filter(_._2).map(_._1)
但这感觉不可读。
【问题讨论】:
标签: scala filter functional-programming scala-collections readability
不确定好多少,但您可以使用 collect:
tupleList.collect { case (true, x) => x }
当然还要给 x 一些有意义的名字。如果第一个元素不是布尔值,您甚至可以执行以下操作:
tupleList.collect { case (x, y) if (cond) => y}
并赋予 x 和 y 有意义的名称
【讨论】:
将等价物与偏函数一起使用也有帮助:
tupleList.filter { case (_, snd) => snd }
.map { case (fst, _) => fst }
当 Dotty 通过元组解包到达时,这应该会显着改善。
【讨论】: