Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

elixir - 确定地图是否具有某些键的正确方法(Proper way to determine if a Map has certain keys)

I have a List of required keys (required_keys):

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

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

and a Map (params):

(和地图(参数):)

%{"track" => "bogus", "artist" => "someone"}

and I want to determine if the params has the required_keys .

(我想确定params是否具有required_keys 。)

I'm coming from a Ruby background and iterating seems wrong for Elixir, but not sure how to pattern-match to do this.

(我来自Ruby背景,对于Elixir而言,迭代似乎是错误的,但不确定如何进行模式匹配。)

  ask by Midwire translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use Enum.all?/2 and Map.has_key?/2 :

(使用Enum.all?/2Map.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

(但不确定如何进行模式匹配)

Pattern matching is not possible if required_keys is dynamic.

(如果required_keys是动态的,则无法进行模式匹配。)

If it's a static list, you could use pattern matching:

(如果是静态列表,则可以使用模式匹配:)

iex(6)> match?(%{"artist" => _, "track" => _, "year" => _}, map)
false
iex(7)> match?(%{"artist" => _, "track" => _, "year" => _}, map2)
true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...