Elixir获取地图,其中包含特定字段的最大值

Kot*_*ote 1 functional-programming elixir

我是Elixir编程语言的初学者。

我有一个类似这样的对象:

{
  id: uuid,
  created_at: DateTime.t,
  updated_at: DateTime.t,
  type: my_type
}
Run Code Online (Sandbox Code Playgroud)

假设my_type是其中之一~w[A B C D]

我想编写一个函数,其中包含这些对象的列表并返回以下映射:

%{
  A: 120,
  B: 220,
  C: 560,
  D: 0,
  any: 560
} 
Run Code Online (Sandbox Code Playgroud)

此外,这里的值还必须是每+ updated_atcreated_atcolumn(Timex.diff(updated_at, created_at, :seconds))之间的最大差。在的情况下,在不考虑并采取列表中的所有对象之间的最大值。my_typeanyanymy_type

在Elixir中做这件事的最好方法是什么?谢谢。

Dog*_*ert 5

下面将按列表的类型对列表进行分组,然后计算每个组的最大差异,最后生成一个映射,其中包含每种类型作为键,最大差异作为值。

map = list
|> Enum.group_by(& &1.type)
|> Enum.map(fn {type, values} ->
  max =
    values
    |> Enum.map(fn %{created_at: created_at, updated_at: updated_at} ->
      # return the difference here
    end)
    |> Enum.max
  {type, max}
end)
|> Map.new
Run Code Online (Sandbox Code Playgroud)

这应该给你类似的东西:

%{
  A: 120,
  B: 220,
  C: 560,
  D: 0
}
Run Code Online (Sandbox Code Playgroud)

您可以执行以下操作来any立即计算值map |> Map.values |> Enum.max