"b"} false iex(13)> "b" in %{"a" => "b"} false iex(14)>-6ren">
gpt4 book ai didi

elixir - `in` 运算符如何使用 map ?

转载 作者:行者123 更新时间:2023-12-02 08:19:14 25 4
gpt4 key购买 nike

in 运算符如何与 map 配合使用?

iex(12)> "a" in %{"a" => "b"}
false
iex(13)> "b" in %{"a" => "b"}
false
iex(14)> {"a", "b"} in %{"a" => "b"}
true
iex(15)> {"a", "a"} in %{"a" => "b"}
false

如果它仅对表示键和值的元组返回 true,为什么它在前两次调用中不会引发错误?

最佳答案

如果您查看 in/2 的文档它指出:

This operator (which is a macro) simply translates to a call to Enum.member?/2.

Enum.member?/2适用于任何 Enumberable。

The implementation of member?/2 map 的可枚举协议(protocol)所需:

  def member?(map, {key, value}) do
{:ok, match?({:ok, ^value}, :maps.find(key, map))}
end

def member?(_map, _other) do
{:ok, false}
end

您可以使用以下代码看到映射的其他实例被转换为 Enumerable 协议(protocol)的元组:

iex(4)> Enum.map(%{"a" => "b", 1 => 2}, & &1)
[{1, 2}, {"a", "b"}]

关于elixir - `in` 运算符如何使用 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com