docs

您正在閱讀 v0.1.0 的文件。Nabi 0.1.0 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#Generators

本頁內容

Write the Fibonacci sequence, a prime stream, a hand-made take_while adapter and a recursive tree walk as lazy iterators with yield fn.

#Code

#Walkthrough

  • Calling a yield fn doesn't run its body right away; it returns an iterator, GenIter<T>. The -> i64 is not a return value but the type of the yielded items (4.11.3 named generator functions).
  • fibonacci() and primes() are infinite generators. Their locals (a, b, found) are preserved between yields, and the consumer pulls only as many items as it needs with take, nth and the like (4.11.9 infinite generators).
  • Generators implement Iterator, so they combine with adapters such as filter, sum and to_list. Written by hand, take_while (the standard iterator has one too) is a single generic yield fn that ends iteration with return; (Collections and iterators, Generics).
  • yield { ... } is an inline generator block that builds an iterator right where an expression is expected (4.11.4).
  • leaves calls itself and re-yields the values of each subtree. Recursive generators are a common way to flatten nested structures (Sum types).

Note

An enum that contains itself directly, like Node(Tree, i64, Tree), has infinite size, so the compiler rejects it (recursive type `Tree` has infinite size). This example keeps the children in a List<Tree>, a reference type, to express the same structure.

Found a mistake? Edit this page on GitHub. Last updated