前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >《Kotlin极简教程》第六章 Kotlin函数式编程(FP)函数指针复合函数

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

作者头像
一个会写诗的程序员
发布2018-08-20 10:49:17
3670
发布2018-08-20 10:49:17
举报

Kotlin对函数式编程的实现恰到好处。

正式上架:《Kotlin极简教程》Official on shelves: Kotlin Programming minimalist tutorial

函数指针

代码语言:javascript
复制
/**
 * "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的实现相当简洁。(跟纯数学的表达式,相当接近了)

代码语言:javascript
复制
/**
 * 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]

简单说明下

代码语言:javascript
复制
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) )

代码语言:javascript
复制
/**
 * 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)))} 
}

运行结果:

代码语言:javascript
复制
[a, abc]
[a, ab, abc]
[ab, abc]
[ab, abc]
[ab]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 函数指针
  • 复合函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档