简体   繁体   English

Lambda 表达式“非”谓词

[英]Lambda expressions “Not” predicate

I currently on my way to learn Kotlin and hopefully becoming a developer but I am stuck on a problem and can not figure out the answer (even after extensive google research).我目前正在学习 Kotlin 并希望成为一名开发人员,但我遇到了一个问题,无法找出答案(即使经过广泛的谷歌研究)。

It would be much appreciated if somebody could help me and explain their solution.如果有人可以帮助我并解释他们的解决方案,将不胜感激。 :) :)

Thank you in advance!先感谢您!

Question:问题:

"Write a predicate that takes the originalPredicate: (Char) -> Boolean variable and returns the negated result. Your predicate is to filter a string." “编写一个采用 originalPredicate 的谓词:(Char) -> Boolean 变量并返回否定结果。您的谓词是过滤字符串。”

Implementation: val notPredicate: (Char) -> Boolean = TODO("Provide implementation")实现:val notPredicate: (Char) -> Boolean = TODO("提供实现")

So, let's understand the problem first.所以,让我们先了解问题。

You have given originalPredicate: (Char) -> Boolean , so it will return a Boolean value according to the character.您已经给出originalPredicate: (Char) -> Boolean ,因此它将根据字符返回 Boolean 值。 For example, if it will return true for 'a', 'c', 'e', etc. (just an example), then you have to return false for them and true for 'b', 'd', 'f', etc.例如,如果它会为 'a'、'c'、'e' 等返回 true(只是一个示例),那么您必须为它们返回 false,并且为 'b'、'd'、'f 返回 true ', ETC。

So, you wanna call the originalPredicate , know the result (ie true or false) and then inverse the result and then return it.所以,你想调用originalPredicate ,知道结果(即真或假),然后反转结果,然后返回它。

val notPredicate: (Char) -> Boolean = { char ->
    val booleanValue = originalPredicate(char)
    return@notPredicate !booleanValue
}

If you simplify the steps, and use it which is default name of variable inside lambda, and since last statement in the lambda is returned by itself (so you don't have to write explicit return):如果您简化步骤,并使用it作为 lambda 中变量的默认名称,并且由于 lambda 中的最后一条语句自行返回(因此您不必编写显式返回):

val notPredicate: (Char) -> Boolean = { !originalPredicate(it) }

Do you mean this:你是这个意思吗:

val originalPred :(Char) -> Boolean =  {it>'a'}
val somePred :(Char) -> Boolean =  {!originalPred.invoke(it)}

Note, the it>'a' is just an example.注意, it>'a'只是一个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM