【问题标题】:Exclude results from List Comprehensions in Elixir从 Elixir 中的 List Comprehensions 中排除结果
【发布时间】:2019-04-21 04:47:58
【问题描述】:

我有一个简单的列表理解:

for x <- [some_list] do
  case _compute(x) do
    nil -> nil # directly exclude this value from output
    val -> val # add this value to output as usual
  end
end

没有运行整个理解,然后过滤掉 nil 值,有没有更好的方法?

【问题讨论】:

    标签: elixir list-comprehension


    【解决方案1】:

    Comprehensions 支持过滤器、生成器、模式匹配和内置的多个子句。

    过滤nil值:

    for x <- list, !is_nil(x), do: x
    

    对每个值调用一个新函数(并自动过滤nil):

    for x <- list, y = _compute(x), do: y
    

    示例:

    iex> list = [1, 2, 3, nil, 4, 5, 6, nil, 7, 8, nil, 9, nil, 0]
    iex> for x <- list, !is_nil(x), do: x
    # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    iex> compute = fn x -> if x > 5, do: x end
    iex> for x <- list, y = compute.(x), do: y
    # => [6, 7, 8, 9]
    

    【讨论】:

    • 在我的情况下,_compute(x) 可能会给出一个值或 nil,因此我需要运行 _compute(x) 两次:即测试 _compute(x) 是否为 nil,然后执行:_compute(x)跨度>
    • 无需运行_compute(x) 两次,因为给出的第二种形式将自动过滤nil_compute(x) 返回的值。
    • 我举了上面的例子来说明多个子句是如何工作的,但你可以进一步缩短它:for x &lt;- list, _compute(x), do: x
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 2014-10-09
    相关资源
    最近更新 更多