9.12 构建无穷惰性序列

我们可以使用 buildSequence 序列生成器 ,构建一个无穷惰性序列。

1. val fibonacci = buildSequence {
2. yield(1L)
3. var current = 1L
4. var next = 1L
5. while (true) {
6. yield(next)
7. val tmp = current + next
8. current = next
9. next = tmp
10. }
11. }

我们通过buildSequence创建一个协程,生成一个惰性的无穷斐波那契数列。该协程通过调用 yield() 函数来产生连续的斐波纳契数。

我们可以从该序列中取出任何有限的数字列表,例如

1. println(fibonacci.take(16).toList())

的结果是:

1. [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]