Elixir Enum.max返回last而不是first元素

xij*_*ijo 3 elixir

如果多个元素被认为是最大的,则返回找到的第一个元素. https://hexdocs.pm/elixir/Enum.html#max/2

iex> [4, 0, 4] |> Enum.with_index |> Enum.max
{4, 2}
Run Code Online (Sandbox Code Playgroud)

我原以为这会回来{4, 0},显然我错过了什么?

感谢任何帮助,以清理我的困惑:)

Dog*_*ert 7

那是因为之后|> Enum.with_index,你的列表是[{4, 0}, {0, 1}, {4, 2}]{4, 2}{4, 0}比较元组时更大,当第一个元素相等时,第二个元素(然后是第三个元素)进行比较.

测试你试图测试的东西的正确方法是使用Enum.max_by/2这样的:

iex(1)> [4, 0, 4] |> Enum.with_index |> Enum.max_by(fn {x, i} -> x end)
{4, 0}
Run Code Online (Sandbox Code Playgroud)