【问题标题】:Subtracting one Stream from the other从另一个流中减去一个流
【发布时间】:2017-11-26 07:23:18
【问题描述】:

在 Elixir 中,您可以执行以下操作:

iex> [1,2,3,4] -- [2,3]
[1,4]

Stream 类型有类似函数吗?

试图实现这一点,我有:

  def stream_subtract(enum, []), do: Enum.to_list(enum)

  def stream_subtract(enum1, enum2) do
    head = Stream.take(enum2, 1)
    new_enum1 = Stream.drop_while(enum1, &([&1] == head))
    stream_subtract(new_enum1, Stream.drop(enum2, 1))
  end

但是这失败了,因为[&1] 是一个列表,而不是一个流。

【问题讨论】:

  • 如果你真的想处理实时流 - 其中一个流必须等待另一个流中的相关元素 - 那么 Elixir 的 Flow 可能是前进的方向 hexdocs.pm/flow/Flow.html

标签: stream elixir difference subtraction


【解决方案1】:

您需要提前收集第二个流,以便测试其中是否存在元素。以下是您如何将其收集到 MapSet 中,然后使用它过滤第一个流。

另外,Stream.drop_while 只会从流的开头删除。如果你想从任意位置下降,你需要使用Stream.reject

# Our two streams
foo = 1..10 |> Stream.take(4)
bar = 1..10 |> Stream.drop(1) |> Stream.take(2)

# Collect the second stream into a MapSet
bar = bar |> Enum.into(MapSet.new)

# Filter the first stream and print all items:
foo = foo |> Stream.reject(fn x -> x in bar end)
for f <- foo, do: IO.inspect(f)

输出:

1
4

【讨论】:

  • 谢谢 - 在这里使用 MapSet 对我来说特别有教育意义。
猜你喜欢
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2013-02-21
相关资源
最近更新 更多