Range Over Iterators in Nim
Our example demonstrates the use of the Range
feature on iterators, showcasing a series of operations on a list, and generating Fibonacci numbers. Here’s how you can achieve similar functionality in Nim:
Let’s break down the example:
We define two types:
Element
andList
.Element
contains a value and a reference to the next element, whileList
contains references to the head and tail of the list.The
push
procedure appends a new value to the end of the list. If the list is empty, it initializes bothhead
andtail
with the new element. If not, it adds the new element to the end and updatestail
.The
all
procedure returns an iterator. This iterator traverses from the head to the tail, yielding each element’s value.The
genFib
procedure returns an iterator that generates Fibonacci numbers. It continues generating as long as the consumer keeps requesting more numbers by yielding.In the
main
procedure, we create aList
, push some values into it, and then use theall
iterator in a loop to print each value.We collect all values from the list’s iterator into a sequence using
toSeq
and print them.The
genFib
iterator is used in a loop to generate and print Fibonacci numbers until a number greater than or equal to 10 is encountered.
The translated code showcases idiomatic Nim constructs to mimic the original functionality. Nim’s iterators are similar to those in the original code’s language, allowing us to range over custom data structures and infinite sequences seamlessly.