Inverse function in Scala

前端 未结 5 573
自闭症患者
自闭症患者 2021-01-02 23:01

Is there a way to express the inverse of any function in Scala?

For example if I have a function f like this:

(x: Int) => x + 1
         


        
5条回答
  •  情歌与酒
    2021-01-02 23:28

    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 filterNotshould be used instead, but I think that in this example remove just reads better.

提交回复
热议问题