有条件地从 Stream 中获取元素

Conditionally taking elements from a Stream

我实现了以下功能:

  def gaussian(center, height, width) do
    Stream.iterate(1, &(&1 + 1))
    |> Stream.map(fn (x) -> x - center end)
    |> Stream.map(fn (x) -> :math.pow(x, 2) end)
    |> Stream.map(fn (x) -> -x / (2 * :math.pow(width, 2))  end)
    |> Stream.map(fn (x) -> height * :math.exp(x) end)
    |> Stream.map(&Kernel.round/1)
    |> Stream.take_while(&(&1 > 0))
    |> Enum.to_list                                                            
  end

对于给定的参数,返回一个空列表:

iex> gaussian(10, 10, 3)
[]

删除 Stream.take_while/2

  def gaussian(center, height, width) do
    Stream.iterate(1, &(&1 + 1))
    |> Stream.map(fn (x) -> x - center end)
    |> Stream.map(fn (x) -> :math.pow(x, 2) end)
    |> Stream.map(fn (x) -> -x / (2 * :math.pow(width, 2))  end)
    |> Stream.map(fn (x) -> height * :math.exp(x) end)
    |> Stream.map(&Kernel.round/1)
    #|> Stream.take_while(&(&1 > 0))                                                   
    #|> Enum.to_list                                                                   
    |> Enum.take(20)
  end

但是给出了这个:

iex> gaussian(10, 10, 3)
[0, 0, 1, 1, 2, 4, 6, 8, 9, 10, 9, 8, 6, 4, 2, 1, 1, 0, 0, 0]

我的 Stream.take_while/2 调用有问题吗,还是我在这里完全遗漏了什么?

Stream.take_while/2 在第一次出现计算为 false.

的函数时停止计算

在你的例子中,你的函数在:

|> Stream.take_while(&(&1 > 0))

使用指定的参数,如

gaussian(10, 10, 3)

在第一次迭代中收到 0 因此它不会进一步迭代,因为您的表达式 &1 > 0 计算为 false.

如果将代码扩展为类似以下内容,您可以自行检查:

|> Stream.take_while(fn (x) -> IO.inspect(x); x > 0 end)

也许它 Stream.filter/2 你想用?

希望能帮助您解决问题![​​=21=]