Tag: 功能编程

Kotlin数据类成员函数的记忆

在下面的Kotlin示例中,我想“memoize”(缓存结果)成员函数matches : import java.util.regex.Pattern data class MyDataClass(val name: String = "John Doe", val description: String = "Famous person") { //TODO memoize this fun matches(searchTerm: String): Boolean { println("Calculating…") return name.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex()) || description.matches("(?i).*${Pattern.quote(searchTerm)}.*".toRegex()) } } fun main(args: Array<String>) { val myData = MyDataClass() println(myData.matches("John")) println(myData.matches("John")) println(myData.matches("John")) println(myData.matches("Famous")) println(myData.matches("Famous")) println(myData.matches("Famous")) } 据我所知,Kotlin <= 1.1不支持记忆。 当然,你可以编写自己的memoization函数或者使用像https://github.com/MarioAriasC/funKTionale这样的库 使用funKTionale,我不必编写我自己的记忆功能,来到这个解决方案。 不幸的是它看起来是“板甲”: […]

Kotlin – 将while循环转换为功能样式

我有以下Kotlin函数: fun func(n: Int): Int { var count = 1 var m = n while(m != 1) { m = if(m.isOdd()) 3 * m + 1 else m / 2 count++ } return count } 我想用一个“功能”风格来写这个简单的算法,使用像map(),count()等Kotlin的操作符。我能想到的最接近的是: fun func(n: Int): Int { return n.toList() .map{ if(it.isOdd()) 3*it+1 else it/2 } .takeWhile { it != 1 } […]

如何在Kotlin中实现一个java SAM接口?

在Java中,可以像这样编写代码: model.getObservableProduct().observe(this, new Observer<ProductEntity>() { @Override public void onChanged(@Nullable ProductEntity productEntity) { model.setProduct(productEntity); } }); 然而,试图在Kotlin中覆盖本地函数的结果是: 问题:可以重写Kotlin中的本地函数吗?

在Kotlin中的功能循环中,如何做“休息”或“继续”?

在Kotlin中,我不能在函数循环和lambda中continue break或continue ,就像我可以从一个普通的for循环一样。 例如,这不起作用: (1..5).forEach { continue@forEach // not allowed, nor break@forEach } 有一些旧的文档提到这个可用,但它似乎从来没有实现。 当我想要在lambda内continue或break时,获得相同行为的最佳方法是什么? 注意: 这个问题是由作者故意写的和回答的( 自我回答的问题 ),所以对于常见的Kotlin话题的习惯性的回答是在SO中。 此外,为了澄清一些真正的古老的答案写为科特林的阿尔法,是不是今天的Kotlin准确。

如何在Kotlin中使用递归类型

我想要做的是这样的事情 fun <F, A, R> recur(f: (F, A) -> R, arg: A): R = f(f, arg) where F = (F, A) -> R 如何在Kotlin中输入这个函数?