How to use / refer to the negation of a boolean function in Scala?

前端 未结 4 1356
梦如初夏
梦如初夏 2020-12-23 21:51

I\'m trying to use the negation of a boolean function in Scala, such as:

def someFunction(x: Set, p: Int => Boolean): Boolean = 
    someOtherFunction(x,          


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 22:09

    Another way to solve it without the use of an anonym function is to define a concrete function for this task.

    def even(x:Int):Boolean = x%2==0
    def not(f: Int => Boolean): Int => Boolean = !f(_)
    def odd = not(even)
    odd(1) // true
    odd(2) // false
    

    You can also define ! yourself

    def even: Int => Boolean = _%2==0
    implicit def bangy(f: Int => Boolean) = new { def unary_! : Int => Boolean = !f(_) }
    def odd = !even
    odd(1) // true
    odd(2) // false
    

    but this only seems to works for functions of type Int=>Boolean, and not (Int)=>Boolean. The not(even) solution works with both.

提交回复
热议问题