Kotlin - 函数组合 - 解释

Kotlin - function composition - explanation

我正在关注 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 is passed to greaterThanThree(8) evaluates to -> true
// then the confusing part for me is that according to the logic above true would be passed to even which makes no sense

even(true)

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

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

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

在函数定义体中

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

g 使用参数 x 调用,因此 x 应该是 Intg(x) return 是 Boolean.

但是,f 是以 g 的 return 值作为参数调用的。 由于f需要一个Intgreturn一个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