【问题标题】:Merge Enum.map response in a single list在单个列表中合并 Enum.map 响应
【发布时间】:2018-02-01 17:07:21
【问题描述】:

在以下示例中,我 Enum.map 一个列表,根据某些条件,我可以收到单个项目或项目列表。 如果我只收到一件物品,我将最终拥有一份清单。 但是,如果我还收到另一个列表,我将拥有一个嵌套列表。

defmodule TestQuery do

  def build_query() do
    Enum.map(["test1", "test2", "hello"], fn item ->
      query(item)
    end)
  end

  def query(item) do
    case String.contains? item, "test" do
      true -> 1
      false -> [2, 3]
    end
  end

end

iex(2)> TestQuery.build_query
[1, 1, [2, 3]]

如何将false 上的列表输出合并为一个列表? [1、1、2、3]

想像在true 我查询一个项目,在false 我查询多个项目,但我想将它们加入同一个列表。

【问题讨论】:

  • List.flatten([1, 1, [2, 3]]) == [1, 1, 2, 3]

标签: elixir


【解决方案1】:

重构你的build_query/0 看起来像这样:

def build_query() do
  ["test1", "test2", "hello"] # this is a style change only
  |> Enum.map(fn item -> query(item) end)
  |> List.flatten # here's the thing that make this list flat
end

请参阅List.flatten:https://hexdocs.pm/elixir/List.html#flatten/1 上的文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2016-05-05
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多