【问题标题】:Filtering list of tuples - better readability过滤元组列表 - 更好的可读性
【发布时间】:2017-09-17 02:51:39
【问题描述】:

什么是过滤元组列表的好方法(阅读更好的可读性)。我正在使用

tupleList.filter(_._2).map(_._1)

但这感觉不可读。

【问题讨论】:

  • 能否提供样本数据?

标签: scala filter functional-programming scala-collections readability


【解决方案1】:

不确定好多少,但您可以使用 collect:

tupleList.collect { case (true, x) => x }

当然还要给 x 一些有意义的名字。如果第一个元素不是布尔值,您甚至可以执行以下操作:

tupleList.collect { case (x, y) if (cond) => y}

并赋予 x 和 y 有意义的名称

【讨论】:

    【解决方案2】:

    将等价物与偏函数一起使用也有帮助:

    tupleList.filter { case (_, snd) => snd }
             .map { case (fst, _) => fst }
    

    当 Dotty 通过元组解包到达时,这应该会显着改善。

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 2011-05-27
      相关资源
      最近更新 更多