Our first program will explore iterating over data and returning an iterator. This lets us range over pretty much anything in the data structure! Here’s the full source code.
In this example, we define a List class in Crystal that can store elements. The all method in the List class returns an iterator. This iterator can be used in a loop to range over all the elements of the list.
We also create a gen_fib function, which returns an iterator over Fibonacci numbers. This keeps running as long as the yield keeps returning true.
To add elements to the list, we create an instance of List and use the push method. We then range over the list using the returned iterator from the all method.
Lastly, we generate and print Fibonacci numbers using the gen_fib function.
This example illustrates the power and flexibility of iterators in Crystal, making it easy to range over custom data structures and implement complex iteration logic seamlessly.