You cannot express the inverse of a function, but you can express the inverse of its result and perhaps that would suit you.
This can be useful when you are passing the function around.
For example, if you have a function f: Int => Boolean
that you're using as a parameter in a higher order function, you can wrap it in another function of the same type x => !f(x)
that justs returns the inverse of the computed 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)
/* using select with some conditions */
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)
/* using remove with the same conditions */
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: method remove
in class List
is deprecated and filterNot
should be used instead, but I think that in this example remove
just reads better.