在 Elixir 中通过内部映射值查找键

Ale*_*dro 1 elixir

让我们假设我有:

%{apple: %{color: red, id: 1}, pear: %{color: green, id: 2}}

按值循环获取密钥(例如苹果)的最快方法是什么(例如,颜色:红色)

Bre*_*tty 7

理解使过滤/映射变得容易:

iex> red = :red
:red
iex> green = :green
:green
iex> fruits = %{apple: %{color: red, id: 1}, pear: %{color: green, id: 2}}
%{apple: %{color: :red, id: 1}, pear: %{color: :green, id: 2}}
iex> for {fruit, %{color: ^red}} <- fruits, do: fruit
[:apple]
Run Code Online (Sandbox Code Playgroud)

我们可以利用可枚举的映射({key, value}成对)来选择值与某种模式匹配的所有键。