関数の逆関数を表現することはできませんが、その結果の逆関数を表現することはできます。おそらくそれが適しています。
これは、関数を渡すときに便利です。
たとえば、f: Int => Boolean
高階関数のパラメーターとして使用している関数がある場合x => !f(x)
、計算結果の逆関数を返すだけの同じタイプの別の関数でラップできます。
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)
注:remove
クラスのメソッドList
は非推奨であり、代わりに使用する必要がありますが、この例では読みやすくなっfilterNot
ていると思います。remove