我对 generateSequence
感到困惑在 Kotlin 。我好像读错了手册:
这是函数签名(对于带种子的 generateSequence
):
fun <T : Any> generateSequence(
seed: T?,
nextFunction: (T) -> T?
): Sequence<T>
所以 Sequence
应该是相同类型的种子,因此下一个值应该进入下一个迭代生成....
但是man中的例子是:
fun fibonacci(): Sequence<Int> {
return generateSequence(Pair(0, 1), { Pair(it.second, it.first + it.second) }).map { it.first }
}
println(fibonacci().take(10).toList()) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
所以看起来 Sequence
的类型是Int
种子是Pair<Int, Int>
.
生成器函数映射Pair<Int, Int>
收件人 Int
.
下一个值是如何发送到生成器的,下一个 Pair<Int, Int>
在哪里?构造(生成器的输出是Int
...)?
这个函数到底是怎么知道什么时候停止的?生成器永远不会返回 null
最佳答案
So it would seem that the type of the Sequence is Int the seed is Pair.
给定的 fibonacci()
函数使用 generateSequence()
生成一个 Pair
序列,然后使用 map
函数将该序列转换为 Int
序列。
val pairs = generateSequence(Pair(0, 1), { Pair(it.second, it.first + it.second) })
// (0,1), (1,1), (1,2), (2,3), (3,5), (5,8) ...
val ints = pairs.map { it.first }
// 0, 1, 1, 2, 3, 5
如果这有助于您思考,您可以想象“完整的”第一个序列是在任何对转换为整数之前生成的。
And how on earth does the function know when to stop?
事实并非如此。但是这个例子使用了 the take()
function将序列截断为前 10 个项目,然后打印它而不是打印无限序列。
序列惰性
;它只在需要时生成值(通过调用给定的生成器函数)。所以当 generateSequence()
返回时,它还没有生成任何东西——只是创建了一个可以这样做的序列。类似地,当应用于一个序列时,map()
调用不会立即映射任何值,只是返回一个修改后的序列,如果/当任何值生成时,该序列将这样做。只有当 take()
被调用时,序列才会生成(并映射)一些值;并且因为 take() 在 10 个项目后停止,它不会产生更多的东西。
关于kotlin - 我无法理解 Kotlin 中的 generateSequence 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54952226/