Idiomatic iterators

Lionel Cons lionel.cons@REDACTED
Fri Mar 11 12:38:16 CET 2011


<context>

I'm porting some code to Erlang that provides access to a list of "elements".

Since this list can potentially be big, I don't want to return it in one go.

In the other supported languages, we use simple iterators (e.g. first() and next()).

</context>.

What is the most idiomatic way to provide iterators in Erlang?

So far, I thought about the following two approaches.

(1) Provide a function that would call a user supplied function on each
elements in the list. Something like:

  X = mymodule:new(),
  mymodule:iterate(X, fun (E) -> ... end),

(2) Provide a function that creates an iterator and another one that returns
one element at a time (as well as a new iterator to keep state). Something
like:

  X = mymodule:new(),
  I0 = mymodule:iterator(X),
  {I1, E1} = mymodule:next(X, I0),
  {I2, E2} = mymodule:next(X, I1),
  % could end with Ex = undefined

(1) is simpler but it is also more limited as you can only get one element
at a time.

(2) is more flexible and can easily be used in an Erlang-style "loop" but it
requires more code to use.

There are probably other ways to do it, what would be the most idiomatic?

Thanks in advance for your advices.

Lionel Cons


More information about the erlang-questions mailing list