-
9.12 构建无穷惰性序列
-
我们可以使用 buildSequence 序列生成器 ,构建一个无穷惰性序列。
val fibonacci = buildSequence { yield(1L) var current = 1L var next = 1L while (true) { yield(next) val tmp = current + next current = next next = tmp } }
我们通过buildSequence创建一个协程,生成一个惰性的无穷斐波那契数列。该协程通过调用 yield() 函数来产生连续的斐波纳契数。
我们可以从该序列中取出任何有限的数字列表,例如
println(fibonacci.take(16).toList())
的结果是:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
- 留下你的读书笔记
- 你还没登录,点击这里
-
用户笔记留言