如何实现一个无限序列生成器,我可以使用Stream库函数进行操作?
我想用它来生成前n个素数.我有一个有效的递归方法,但我喜欢enumerables和管道好多了.
我在使用生成器的python中看到过这个:
def number_generator():
n = 3
while True:
yield n
n += 2
Run Code Online (Sandbox Code Playgroud)
是否有内置函数在Elixir中生成这样的序列,或者是一个简单的DIY替代品?这种模式在Elixir中有名字吗?
您至少有两个选项可以在Elixir中生成流.最通用的是Stream.unfold
Stream.unfold(3, fn(x) -> {x, x + 2} end)
# or
Stream.unfold(3, &({&1, &1 + 2}))
Run Code Online (Sandbox Code Playgroud)
但在你的情况下,你可以使用更简单的 Stream.iterate
Stream.iterate(3, fn(x) -> x + 2 end)
# or
Stream.iterate(3, &(&1 + 2))
Run Code Online (Sandbox Code Playgroud)
Stream.iterate/2来救援:
generator = Stream.iterate(3, &(&1+2))\n#\xe2\x87\x92\xc2\xa0#Function<61.8243704/2 in Stream.unfold/2>\ngenerator |> Enum.take(5)\n#\xe2\x87\x92 [3, 5, 7, 9, 11]\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
614 次 |
| 最近记录: |