如何在 Scala 中使用/引用布尔函数的否定?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12681616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use / refer to the negation of a boolean function in Scala?
提问by Emre Sevin?
I'm trying to use the negation of a boolean function in Scala, such as:
我正在尝试在 Scala 中使用布尔函数的否定,例如:
def someFunction(x: Set, p: Int => Boolean): Boolean =
someOtherFunction(x, !p)
But I get the error:
但我收到错误:
value unary_! is not a member of Int => Boolean
How can I refer to the negation of p?
我如何引用 p 的否定?
回答by Kim Stebel
The negation of pis a function that applies pto its argument and negates the result.
的否定p是一个应用于p其参数并否定结果的函数。
x => !p(x)
If you want to be able to write !por p && qyou can use this library, which pimps functions that return a bool with various logical operators.
如果您希望能够编写!p或者p && q您可以使用这个库,它会使用各种逻辑运算符返回布尔值的函数。
回答by carlos_lm
Shortest negation of p: !p(_)
p 的最短否定:!p(_)
When you apply the predicate pas an argument to another function:
当您将谓词p作为参数应用于另一个函数时:
- p or p(_) are abbreviations of the lambda expresion: (x) => p(x)
- !p(_) is an abbreviation of the lambda expresion: (x) => !p(x) and with only !p the compiler gets lost.
- p 或 p(_) 是 lambda 表达式的缩写:(x) => p(x)
- !p(_) 是 lambda 表达式的缩写: (x) => !p(x) 并且只有 !p 编译器会丢失。
For example, using a Set of integers (try it on a Scala worksheet):
例如,使用一组整数(在 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
回答by Istador
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.
但这似乎只适用于 Int=>Boolean 类型的函数,而不适用于 (Int)=>Boolean。not(even) 解决方案适用于两者。

