[erlang-questions] iterators in Erlang

Serge Aleynikov <>
Wed Oct 25 16:25:31 CEST 2006


Perhaps this is because of the intent to keep functions pure functional?

xrange seems to rely on side-effects (i.e. storing internally the 
current element counter) that may cause issues with concurrency. 
However, it can be safely implemented in a separate process.

It would indeed be nice if such a construct existed in Erlang/OTP.  This 
would be similar to OCaml streams.  Streams are sequences of elements 
(that can potentially be infinite). The evaluation of a part of a stream 
is done in a lazy manner on demand, whenever it is needed by the current 
computation.

Examples could be that you initialize a stream with a string, file, 
socket or some other generator, and use it just like a list by fetching 
one element (or binary pattern) at a time:

process_stream ( make_stream({file, FileName}) ).

process_stream([:  :]) ->
   io:put_chars("\n");
process_stream([: Ch | Tail :]) ->
   io:format("~c ", [Ch]),
   process_stream(Tail).

Regards,

Serge

James Hague wrote:
> I've recently been brushing up on my Python, because I'm teaching a
> class using it.  What's surprising to me is how much modern Python
> relies on iterators (an "iterator" being an object that returns one
> value at a time in a sequence).  Where lists:seq(1,100000) returns a
> large list in erlang, xrange(1,100000+1) in Python generates one value
> at a time.  Then you can sum these values with sum(xrange(1,100000+1))
> and there's still no intermediate list.
> 
> Even more interesting is that iterators have evolved into generators,
> which are a poor man's processes).  People are twisting generators to
> get cooperative multitasking.
> 
> What jumps out at me is how natural this stuff is to do in Erlang, and
> yet the iterator/generator style isn't an inherent part of the Erlang
> libraries.  I'm not sure if it really *should* be, of course, but I
> was curious why Erlang never went down this path.
> 
> James
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 



More information about the erlang-questions mailing list