我有一个必需的键列表(required_keys):
["artist", "track", "year"]
和地图(参数):
%{"track" => "bogus", "artist" => "someone"}
我想确定params
是否有required_keys
。我来自Ruby背景并且迭代似乎对Elixir不合适,但不确定如何进行模式匹配来做到这一点。
答案 0 :(得分:5)
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
但不确定如何进行模式匹配
如果required_keys
是动态的,则无法进行模式匹配。如果它是静态列表,您可以使用模式匹配:
iex(6)> match?(%{"artist" => _, "track" => _, "year" => _}, map)
false
iex(7)> match?(%{"artist" => _, "track" => _, "year" => _}, map2)
true
答案 1 :(得分:1)
requireds = ["artist", "track", "year"]
params = %{"track" => "bogus", "artist" => "someone"}
Enum.all?( requireds, fn(k) -> Map.has_key?(params, k) end) # => false
requireds = ["artist", "track"]
Enum.all?( requireds, fn(k) -> Map.has_key?(params, k) end) # => true
或模式匹配:
def has_required_params?(%{"artist" => _, "track" => _, "year" => _}), do: true
def has_required_params?(_), do: false
has_required_params?(%{"track" => "bogus", "artist" => "someone"}) # => false
has_required_params?(%{"track" => "bogus", "artist" => "someone", year => "2000"}) # => true
答案 2 :(得分:0)
使用in
代替Map.has_key?
:
def contains_fields?(keys, fields), do: Enum.all?(fields, &(&1 in keys))