【问题标题】:Kotlin - function composition - explanationKotlin - 函数组合 - 解释
【发布时间】:2021-10-31 20:47:11
【问题描述】:

我正在关注 Kotlin 箭头库上有关函数式编程的一些视频 presentation。我来到了这个函数组合的例子:

val greaterThanThree = { it > 3 } 
val even = { it % 2 == 0 }
val greaterThanThreeAndEven = greaterThanThree compose even

那么它可以用于类似的东西:

list.filter(::greaterThanThreeAndEven)

根据我之前对函数组合的理解,我们将参数传递给第一个函数,然后将返回值传递给第二个函数,如下例所示:

fun compose(f: (Int) -> Boolean, g: (Int) -> Boolean): (Int) -> Boolean = {
                                                                   x -> f(g(x)) }

所以,我不知道我是否做对了,因为我还没有处理函数式编程,但我认为步骤是这样的:

val x = 8 被传递给 greaterThanThree(8) 计算结果为 -> true
// 那么对我来说令人困惑的部分是根据上面的逻辑 true 将被传递给 even 这没有任何意义

偶数(真)

谁能解释一下这两个函数是如何组合的以及这个组合函数的步骤是什么:

{ it > 3 && it % 2 == 0 } 

【问题讨论】:

  • 你能链接到源吗?我不知道 Kotlin,但这看起来不像我见过的任何类型的函数组合......
  • @JaredSmith 这是关于箭头库的视频教程,其中显示了 GreaterThanThree 甚至示例,示例从这里开始:youtu.be/tM2wEI-e80E?t=157
  • 是的,那是……不同?假设这些函数是正确的,那取决于 Kotlin 如何处理不应该编译(类型不匹配)或将编译但给出错误答案的布尔值(在某些语言中它们是 int 的子类)。
  • 这段代码编译是否没有任何错误?

标签: kotlin functional-programming function-composition


【解决方案1】:

compose 不是&&,它是嵌套函数调用。

在函数定义的主体中

fun compose(f: (Int) -> Boolean, g: (Int) -> Boolean): (Int) -> Boolean = { x -> f(g(x)) }

g 使用参数x 调用,因此x 应该是Int,而g(x) 返回Boolean

但是,fg 的返回值作为参数调用。 由于f 需要Intg 返回Boolean,编译器会报错:

error: type mismatch: inferred type is Boolean but Int was expected

如果你想编写布尔函数,这可能是一个例子,

fun booleanCompose(
    f: (Int) -> Boolean,
    g: (Int) -> Boolean,
    op: (Boolean, Boolean) -> Boolean,
): (Int) -> Boolean = {
    x -> op(f(x), g(x))
}

val greaterThanThree: (Int) -> Boolean = { it > 3 }
val even: (Int) -> Boolean = { it %2 == 0 }

val and: (Boolean, Boolean) -> Boolean = { b1, b2 -> b1 && b2 }

val greaterThanThreeAndEven = booleanCompose(greaterThanThree, even, and)

为了允许您使用的语法,需要一个扩展中缀函数:

infix fun ((Int) -> Boolean).and(g: (Int) -> Boolean): (Int) -> Boolean = 
    booleanCompose(this, g, and)

val greaterThanThreeAndEven = greaterThanThree and even

【讨论】:

  • 是的,看起来不错,我真的对箭头教程中的那个例子感到困惑,这太奇怪了,他们使用的例子甚至无法编译,因为很容易混淆像这样的菜鸟我有这样错误的例子。
  • @Leff 我绝对不认为自己是 FP 的新手,这让我很困惑。我认为这只是令人困惑的大声笑。
  • @JaredSmith 令人欣慰
猜你喜欢
  • 1970-01-01
  • 2017-09-20
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多