Use Enum.all?/2
and Map.has_key?/2
:
(使用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
(但不确定如何进行模式匹配)
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…