Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
生成惰性列表的Elixir函数_Elixir - Fatal编程技术网

生成惰性列表的Elixir函数

生成惰性列表的Elixir函数,elixir,Elixir,使用已知数量的流与此答案相关: 如何构建一个create_stream函数,以类似的方式嵌套任意数量的流,即: create_stream([1..1_000_000, 1..5_000_000]) #should be equivalent to: Stream.flat_map 1..1_000_000, fn i -> Stream.flat_map 1..5_000_000, fn j -> [{i, j}] end end 及 这很可能不如手动嵌套St

使用已知数量的流与此答案相关:

如何构建一个create_stream函数,以类似的方式嵌套任意数量的流,即:

create_stream([1..1_000_000, 1..5_000_000]) 

#should be equivalent to:
Stream.flat_map 1..1_000_000, fn i ->
  Stream.flat_map 1..5_000_000, fn j ->
    [{i, j}]
  end
end


这很可能不如手动嵌套
Stream.flat_map/2
有效,但它可以处理任意数量的流:

defmodule MyStream do
  def combine(list), do: combine(list, [])

  defp combine([h], acc) do
    Stream.map(h, fn x ->
      [x | acc] |> Enum.reverse |> List.to_tuple
    end)
  end
  defp combine([h | t], acc) do
    Stream.flat_map(h, fn x ->
      combine(t, [x | acc])
    end)
  end
end

expected = for a <- 1..2, b <- 3..4, c <- 5..6, d <- 7..8, do: {a, b, c, d}
actual = [1..2, 3..4, 5..6, 7..8] |> MyStream.combine |> Enum.to_list |> IO.inspect
IO.inspect actual == expected
defmodule MyStream do
  def combine(list), do: combine(list, [])

  defp combine([h], acc) do
    Stream.map(h, fn x ->
      [x | acc] |> Enum.reverse |> List.to_tuple
    end)
  end
  defp combine([h | t], acc) do
    Stream.flat_map(h, fn x ->
      combine(t, [x | acc])
    end)
  end
end

expected = for a <- 1..2, b <- 3..4, c <- 5..6, d <- 7..8, do: {a, b, c, d}
actual = [1..2, 3..4, 5..6, 7..8] |> MyStream.combine |> Enum.to_list |> IO.inspect
IO.inspect actual == expected
[{1, 3, 5, 7}, {1, 3, 5, 8}, {1, 3, 6, 7}, {1, 3, 6, 8}, {1, 4, 5, 7},
 {1, 4, 5, 8}, {1, 4, 6, 7}, {1, 4, 6, 8}, {2, 3, 5, 7}, {2, 3, 5, 8},
 {2, 3, 6, 7}, {2, 3, 6, 8}, {2, 4, 5, 7}, {2, 4, 5, 8}, {2, 4, 6, 7},
 {2, 4, 6, 8}]
true