我有一个简单的列表理解:
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
值,这样做有更好的方法吗?
答案 0 :(得分:3)
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]