《Kotlin极简教程》第六章 Kotlin函数式编程(FP)

Kotlin对函数式编程的实现恰到好处。
最新上架!!!
《 Kotlin极简教程》 陈光剑 (机械工业出版社):
https://mp.weixin.qq.com/s/bzRkGSO6T1O2AELM_UqKUQ

函数指针

/**
 * "Callable References" or "Feature Literals", i.e. an ability to pass
 * named functions or properties as values. Users often ask
 * "I have a foo() function, how do I pass it as an argument?".
 * The answer is: "you prefix it with a `::`".
 */

fun main(args: Array<String>) {
    val numbers = listOf(1, 2, 3)
    println(numbers.filter(::isOdd))
}

fun isOdd(x: Int) = x % 2 != 0

运行结果: [1, 3]

复合函数

看了下面的复合函数的例子,你会发现Kotlin的FP的实现相当简洁。(跟纯数学的表达式,相当接近了)

/**
 * The composition function return a composition of two functions passed to it:
 * compose(f, g) = f(g(*)).
 * Now, you can apply it to callable references.
 */

fun main(args: Array<String>) {
    val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))
}

fun isOdd(x: Int) = x % 2 != 0
fun length(s: String) = s.length

fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
    return { x -> f(g(x)) }
}


运行结果: [a,abc]

简单说明下

val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))

这就是数学中,复合函数的定义:

h = h(f(g))

g: A->B
f: B->C
h: A->C

g(A)=B
h(A) = f(B) = f(g(A)) = C

只是代码中的写法是:

h=compose( f, g )
h=compose( f(g(A)), g(A) )

/**
 * The composition function return a composition of two functions passed to it:
 * compose(f, g) = f(g(*)).
 * Now, you can apply it to callable references.
 */

fun main(args: Array<String>) {
    val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))
    
    println(strings.filter(::hasA))
    println(strings.filter(::hasB))
    
    val hasBStrings = strings.filter(::hasB)
    println(hasBStrings)
    
    val evenLength = compose(::isEven,::length)
    println(hasBStrings.filter(evenLength))
    
    
}

fun isOdd(x: Int) = x % 2 != 0
fun isEven(x:Int) = x % 2 == 0
fun length(s: String) = s.length
fun hasA(x: String) = x.contains("a")
fun hasB(x: String) = x.contains("b")



fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
    return { x -> f(g(x)) }
}

fun <W,X,Y,Z> compose2( h: (Y) -> Z, f:(X) -> Y,g:(W) -> X): (W) -> Z {
    return  {x -> h(f(g(x)))} 
}



运行结果:

[a, abc]
[a, ab, abc]
[ab, abc]
[ab, abc]
[ab]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

禅与计算机程序设计艺术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值