[erlang-questions] Idiomatic iterators

Rob Harrop <>
Fri Mar 11 12:49:10 CET 2011


Lionel,

There aren't many places in the standard library where you have an 
iterator pattern like (2) - only gb_trees comes to mind.

I prefer something like mymodule:foreach (to be consistent with lists). 
You might also want to consider adding a mymodule:fold operation which 
will allow you to do pretty much all the processing you want on your 
stream of elements.

How big is your list likely to be? Is it something that could start 
taxing the memory of the Erlang process?

Regards,

Rob

On 11/03/11 11:38, Lionel Cons wrote:
> <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
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:
>


More information about the erlang-questions mailing list