Starting with version 1.23, there is support for iterators, which lets us range over pretty much anything!
Let’s look at the List type from the previous example again. In that example, we had an AllElements method that returned a list of all elements in the list. With enumerators, we can do it better - as shown below.
All returns an enumerator, which in OCaml is usually achieved with generator-like functions.
The enumerator function takes another function as a parameter, called yield by convention (but the name can be arbitrary). It will call yield for every element we want to iterate over, and note yield’s return value for a potential early termination.
Iteration doesn’t require an underlying data structure, and doesn’t even have to be finite! Here’s a function returning an enumerator over Fibonacci numbers: it keeps running as long as yield keeps returning true.
The main function demonstrates how to push values to the list and how to use the enumerator.