"bogus", "artist"-6ren">
gpt4 book ai didi

elixir - 确定 Map 是否具有某些键的正确方法

转载 作者:行者123 更新时间:2023-12-01 10:35:12 26 4
gpt4 key购买 nike

我有一个必需 key 列表(required_keys):

["artist", "track", "year"]

和 map (参数):
%{"track" => "bogus", "artist" => "someone"}

我想确定是否 paramsrequired_keys .我来自 Ruby 背景,迭代对于 Elixir 似乎是错误的,但不确定如何进行模式匹配来做到这一点。

最佳答案

使用 Enum.all?/2 Map.has_key?/2 :

iex(1)> map = %{"track" => "bogus", "artist" => "someone"}
%{"artist" => "someone", "track" => "bogus"}
iex(2)> map2 = %{"track" => "bogus", "artist" => "someone", "year" => 2016}
%{"artist" => "someone", "track" => "bogus", "year" => 2016}
iex(3)> required_keys = ["artist", "track", "year"]
["artist", "track", "year"]
iex(4)> Enum.all?(required_keys, &Map.has_key?(map, &1))
false
iex(5)> Enum.all?(required_keys, &Map.has_key?(map2, &1))
true

but not sure how to pattern-match to do this



如果 required_keys,则无法进行模式匹配是动态的。如果是静态列表,则可以使用模式匹配:
iex(6)> match?(%{"artist" => _, "track" => _, "year" => _}, map)
false
iex(7)> match?(%{"artist" => _, "track" => _, "year" => _}, map2)
true

关于elixir - 确定 Map 是否具有某些键的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36775591/

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