Calculate complement of a predicate

When I have to pass a predicate to a function, such as filter and I want the negative of the predicate, sometimes the function includes a cousin such as filterNot, but if it doesn’t, I’d like to complement the predicate. it is of course easy enough just to inline the complementation such as data.filter(p => !predicate(p)), but it seems to me there should already be such a function. I searched for Function.complement and predicate.complement but didn’t find such.

Does it already exist in the standard library?

I’m not sure how I’d write it myself in the general case.

You can further reduce the inlined version with underscore syntax, which would almost always be good enough for me:

data.filter(!predicate(_))

A naive stab at a generic complement operator:

implicit class ComplementablePredicate[T](val f: T => Boolean) extends AnyVal {
  def unary_! : T => Boolean = f.andThen(!_)
}

val p = (_: String).isEmpty
println(Seq("a", "", "b").filter(!p))

Best regards,
Patrick

3 Likes