作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图强制自己在Kotlin中使用函数式编程,并且尽可能避免使用可变的var。通常,对于单元返回函数的临时测试,我只需要对函数内部的内容进行println()
来检查其是否正常工作。但是对于此测试,我需要累积一个字符串,然后最终使用assertEquals(...)
。
像往常一样,我发现自己在封闭范围内声明了var
并使用+=
对其进行累加。 是否存在通过传递/链接函数并消除可变var来实现此功能的更实用的方法? 这里是一些简化但说明性的代码:
inline fun <T> Iterable<T>.forEachFrom(beg:Int, act:(T)->Unit) {
var i=0; if (beg>=0) for (e in this) if (i++ >= beg) act(e)
}
fun main(args:Array<String>) {
val l = listOf("zero", "one", "two", "three", "four")
// print-to-screen test
l.forEachFrom(2){print("$it-")}; println()
// output: two-three-four-
// accumulate-in-var test
var s = ""
l.forEachFrom(2){s += "$it-"}; println(s)
// output: two-three-four-
// Is there a purely functional way, without declaring a mutable var?
// val s = l.forEachFrom(2){accumulator???("$it-")}
// - OR -
// val s = l.forEachFrom(2).accumulator???("$it-")
// println(s)
}
最佳答案
仅使用kotlin-stdlib并保留代码语义(即仅迭代一次)的一种方法是convert the Iterable<T>
to Sequence<T>
并使用 .drop(n)
扩展名:
inline fun <T> Iterable<T>.forEachFrom(beg: Int, act: (T) -> Unit) =
if (beg >= 0)
asSequence().drop(beg).forEach(act) else
Unit
Sequence<T>
并将
buildSequence { ... }
作为回调传递该自定义迭代逻辑到
yield(it)
中:
val sequenceFromCustomFunction = buildSequence {
l.forEachFrom(2) { yield(it) }
}
val s = sequenceFromCustomFunction.fold("") { acc, it -> acc + it + "-" }
关于functional-programming - 在Kotlin的Unit函数中积累功能的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47158107/
我有一个应用程序不断从 TCP/IP 端点接收 XML 消息流。收到每条消息后,应用程序将其内容消化到一组核心数据实体中。这是通过三个上下文结构实现的: 大师(私有(private)队列) Main(
boost docs以此作为如何使用 boost::accumulate 的示例: // The data for which we wish to calculate statistical pro
我是一名优秀的程序员,十分优秀!