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

时间:2012-10-01 21:48:32

标签: scala

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

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

但我收到错误:

 value unary_! is not a member of Int => Boolean

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

4 个答案:

答案 0 :(得分:54)

p的否定是一个将p应用于其参数并否定结果的函数。

x => !p(x)

如果您希望能够写!pp && q,可以使用this library,这些pimps函数会返回带有各种逻辑运算符的bool。

答案 1 :(得分:14)

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

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

  • p或p(_)是λ表达式的缩写:(x)=> p(x)
  • !p(_)是lambda表达式的缩写:(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

答案 2 :(得分:3)

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

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

你也可以定义!自己

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

但这似乎只对Int =>类型的函数有效,而不是(Int)=>布尔值。非(偶数)解决方案适用于两者。

答案 3 :(得分:2)

Istador提出的>>> window([1,2,3,4,5,6], 3, 0) Window(index=0, backward=[], forward=[2, 3, 4]) >>> window([1,2,3,4,5,6], 3, 5) Window(index=5, backward=[3, 4, 5], forward=[]) 函数运行良好,但是我认为我们可以更好地利用通过泛型实现的多态性!

not

然后我们可以将其用于def not[T](f: T => Boolean): T => Boolean = x => !f(x) 之类的Int => Boolean函数

isEven

将其用于def isEven(x: Int): Boolean = x % 2 == 0 val numbers = List(1,2,3,4,5,6,7,8,9,10) val evens = numbers filter isEven val odds = numbers filter not(isEven _) // if you actually wanted both, use partition instead // val (evens2, odds2) = numbers partition isEven 函数,如下所示:

String => Boolean

有些人为的,但是老实说,我不确定为什么多态def startsWith(prefix: String)(text: String) = text.startsWith(prefix) val fruits = List("apple", "banana", "cranberry") val bFruits = fruits filter startsWith("b") val notBFruits = fruits filter not(startsWith("b")) 函数没有内置到标准库中? ?

顺便说一句,我也正在Coursera上上Odersky教授的Scala课!