You cannot express the inverse of a function, but you can express its result, and perhaps this will suit you.
This can be useful when you pass a function around.
For example, if you have a function f: Int => Boolean , which you use as a parameter in a higher-order function, you can wrap it in another function of the same type x => !f(x) , which simply returns the opposite result calculation result:
def select(ls: List[String], p: String => Boolean): List[String] = ls.remove(x => !p(x)) // select: (ls: List[String], p: String => Boolean)List[String] val li = List("one", "two", "three") // li: List[java.lang.String] = List(one, two, three) select(li, _.length() > 3) // equivalent to select(li, x => x.length() > 3) // res0: List[String] = List(three) select(li, _.length() <= 3) // equivalent to select(li, x => x.length() <= 3) // res1: List[String] = List(one, two) li.remove(_.length() > 3) // equivalent to li.remove(x => x.length() > 3) // res2: List[java.lang.String] = List(one, two) li.remove(_.length() <= 3) // equivalent to li.remove(x => x.length() <= 3) // res3: List[java.lang.String] = List(three)
NOTE: the remove method in the List class is deprecated and filterNot should be used instead, but I think that in this example, remove simply reads better.
source share