代码之家  ›  专栏  ›  技术社区  ›  Carsten

为什么Scala没有withFilterNot?

  •  1
  • Carsten  · 技术社区  · 7 年前

    Seq ,我们有方法 filter 为了方便起见, filterNot

    seq.filterNot(someSet.contains)
    

    而不是不那么优雅的

    seq.filter(e => !someSet.contains(e))
    

    除了这些方法,我们还有 WithFilter 类,以便能够惰性地评估筛选条件。方便的是,用法与 :

    seq.withFilter(e => !someSet.contains(e))
    

    withFilterNot 这样地:

    seq.withFilterNot(someSet.contains)
    

    更具体地说:这只是Scala开发人员认为不必要/低优先级的特性,还是有技术原因?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dima    7 年前

    你可以写得更短: seq.filterNot(someSet)

    .withFilterNot

    object PimpSyntax {
       implicit class PimpedSeq[T](val seq: Seq[T]) extends AnyVal {
          def withFilterNot(filter: T => Boolean) = seq.withFilter(!f(_))
       }
    }
    

    现在,只是 import PimpSyntax._ ,你可以写这样的东西 seq.withFilterNot(someSet) 只要你喜欢。

    或者,更好的是:

     object PimpSyntax {
         implicit class Negator[T](val f: T => Boolean) extends AnyVal {
            def unary_!: T => Boolean = !f(_)
         }
     }
    

    有了这个,你不仅可以 seq.withFilter(!someSet) seq.partition(!someSet) , seq.find(!someSet) seq.dropWhile(!someSet)

    推荐文章