I have a List of 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
. I'm coming from a Ruby background and iterating seems wrong for Elixir, but not sure how to pattern-match to do this.
Use Enum.all?/2
and 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. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With