简体   繁体   中英

Generate infinite sequence in 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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM