Elixir 左外侧与长生不老药接合';这是为了理解

Elixir 左外侧与长生不老药接合';这是为了理解,elixir,Elixir,我一直在研究如何使用Enum、Stream和进行理解,我正在努力重现左外连接行为。我可以用Enum.reduce实现一个左外连接函数,但如果有办法用for实现,我宁愿使用它 我知道python支持它,我见过它,我想Elixir的理解是受到python的启发的。我们可以用长生不老药吗 假设我有两个来自外部API或某个json/xml文件的列表: categories = [%{id: 1, name: "beverages"}, %{id: 2, name: "vegetables"}] prod

我一直在研究如何使用
Enum
Stream
进行理解,我正在努力重现左外连接行为。我可以用
Enum.reduce
实现一个左外连接函数,但如果有办法用
for
实现,我宁愿使用它

我知道python支持它,我见过它,我想Elixir的理解是受到python的启发的。我们可以用长生不老药吗

假设我有两个来自外部API或某个json/xml文件的列表:

categories = [%{id: 1, name: "beverages"}, %{id: 2, name: "vegetables"}]
products = [%{name: "ice tea", category: 1}, %{name: "sake", category: 1}]
我想加入他们,得到如下结果:

cat_product == [
  %{category: "beverages", product: "ice tea"},
  %{category: "beverages", product: "sake"},
  %{category: "vegetables", product: "(No product)"}
]
cat_products == [
  %{name: "beverages", products: [list of products]}
  %{name: "vegetables", products: []}
]
比如:

cat_product == [
  %{category: "beverages", product: "ice tea"},
  %{category: "beverages", product: "sake"},
  %{category: "vegetables", product: "(No product)"}
]
cat_products == [
  %{name: "beverages", products: [list of products]}
  %{name: "vegetables", products: []}
]

您的第一个示例不能用外部的for循环优雅地编写,因为左侧列表中可能有多个记录与右侧列表中的多个记录合并。但是,对于原始集合中的每个元素,理解的
最多只能产生一个结果。在这种情况下,更适合使用
Enum.flat\u map

Enum.flat_map categories, fn(c) ->
  case Enum.filter(products, fn(p) -> p.category == c.id end) do
    [] ->
      [%{name: c.name, product: nil}]
    prods ->
      for p <- prods, do: %{name: c.name, product: p.name}
  end
end