Home > Back-end >  Elixir: get a stream over elements of a list?
Elixir: get a stream over elements of a list?

Time:10-18

NOTE: this question was written with the assumption that Streams behave like iterators in other languages. As the accepted answer says - it cannot work this way, because that would require mutable state! So there's not really any reason why you would want to do this.

Original question

I'm learning Elixir, and have what I think is simple question: Is there an idiomatic way to get an stream over a list in Elixir?

There are lots of functions in the Stream module that I can (ab)use to do this:

mylist = [1,2,3]
stream1 = Stream.map(mylist, fn x -> x end)
stream2 = Stream.concat([mylist])
# etc. etc.

But thus far I haven't found anything for this specific purpose - I was expecting something like iter(list) in Python, or vec.into_iter() in Rust. Does Elixir have something like this? Or is it somehow a non-Elixirian* thing to do?

*Is it "Elixian"? "Elixery"? "Elixious"?

CodePudding user response:

For iter to work in the way it works in /, one needs a state to be held in the iterator itself. Being fully immutable, does not allow exactly this.

Depending on the task, it might be achieved in different ways. Stream itself might be treated as an iterator if one needs to iterate through the whole collection, but generally speaking, it’s impossible to pause, do something else and continue to work with an iterator, because iterator cannot hold the current state.

If you were to share the real task you are trying to solve, we would come up with the idiomatic elixirish solution. Check Stream.run/1 and all terminating functions in Enum module for how to deal with the elements in the stream.

  • Related