Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate infinite sequence in Elixir

Tags:

elixir

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?

like image 863
Luca Fülbier Avatar asked Jan 18 '17 18:01

Luca Fülbier


2 Answers

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))
like image 67
Patrick Oscity Avatar answered Oct 06 '22 00:10

Patrick Oscity


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]
like image 29
Aleksei Matiushkin Avatar answered Oct 06 '22 00:10

Aleksei Matiushkin