How can i implement a infinite sequence generator that i can operate on using the Stream
library functions?
I want to use that to generate the first n prime numbers. I have a working recursive approach, but i like enumerables and pipes a lot better.
I have seen this done in python using a generator:
def number_generator():
n = 3
while True:
yield n
n += 2
Is there a built-in function to generate such sequences in Elixir, or a easy DIY alternative? Does this pattern have a name in Elixir?
You have at least two options to generate a stream in Elixir. The most generic is Stream.unfold
Stream.unfold(3, fn(x) -> {x, x + 2} end)
# or
Stream.unfold(3, &({&1, &1 + 2}))
but in your case you can use the simpler Stream.iterate
Stream.iterate(3, fn(x) -> x + 2 end)
# or
Stream.iterate(3, &(&1 + 2))
Stream.iterate/2
comes to the rescue:
generator = Stream.iterate(3, &(&1+2))
#⇒ #Function<61.8243704/2 in Stream.unfold/2>
generator |> Enum.take(5)
#⇒ [3, 5, 7, 9, 11]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With