Lazy list comprehension in Elixir?

那年仲夏 提交于 2019-12-09 17:37:08

问题


Is there a way to make list comprehension lazy in Elixir? If not, is there a way to turn this into a Stream?

my_list = for i <- (1..1000000), j <- (1..1000000), do: {i, j}

This code snippet blows my program by taking too much memory.

I want to apply a filter, map and reduce on my_list.


回答1:


A comprehension is a flat map. So your code is equivalent to:

Stream.flat_map 1..1000000, fn i ->
  Stream.flat_map 1..1000000, fn j ->
    [{i, j}]
  end
end

I have proposed a "stream for" and "parallel for" for future Elixir versions, however it is pending some other improvements to the language.



来源:https://stackoverflow.com/questions/32434530/lazy-list-comprehension-in-elixir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!