如何在Scala中使用/引用布尔函数的否定?

Emr*_*inç 39 scala

我试图在Scala中使用布尔函数的否定,例如:

def someFunction(x: Set, p: Int => Boolean): Boolean = 
    someOtherFunction(x, !p)
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

 value unary_! is not a member of Int => Boolean
Run Code Online (Sandbox Code Playgroud)

我怎样才能提到p的否定?

Kim*_*bel 54

否定p是一个适用p于其论证并否定结果的函数.

x => !p(x)
Run Code Online (Sandbox Code Playgroud)

如果你想能够写,!p或者p && q你可以使用这个库,哪些pimps函数返回一个bool与各种逻辑运算符.

  • @Emre,这是可能的,是的.我可以假设你被困在'存在'的问题上吗? (4认同)

car*_*_lm 14

最短的否定p:!p(_)

将谓词p作为参数应用于另一个函数时:

  • p或p(_)是lambda表达式的缩写:(x)=> p(x)
  • !p(_)是lambda expresion的缩写:(x)=>!p(x),只有!p编译器丢失.

例如,使用一组整数(在Scala工作表上尝试):

  def someOtherFunction (x: Set[Int], p: Int => Boolean):Boolean = x.forall(p)
  def someFunction(x: Set[Int], p: Int => Boolean): Boolean =
    someOtherFunction(x, !p(_))

  val x = Set(1,2,3)
  var p: Int => Boolean = (_ > 0)
  //_ > 0 is an abbreviaton of (x) => x > 0

  someFunction(x, p)        //false
  someOtherFunction(x, p)   //true

  p = _ > 1
  someFunction(x, p)        //false
  someOtherFunction(x, p)   //false

  p = _ > 3
  someFunction(x, p)        //true
  someOtherFunction(x, p)   //false
  println
Run Code Online (Sandbox Code Playgroud)


Ist*_*dor 5

另一种不使用匿名函数来解决它的方法是为此任务定义一个具体的函数。

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
Run Code Online (Sandbox Code Playgroud)

你也可以定义!你自己

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
Run Code Online (Sandbox Code Playgroud)

但这似乎只适用于 Int=>Boolean 类型的函数,而不适用于 (Int)=>Boolean。not(even) 解决方案适用于两者。