本文介绍了确定地图是否具有某些键的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a List of required keys (required_keys):

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

和地图(参数):

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

,我想确定参数具有 required_keys 。我来自Ruby背景,对于Elixir来说,迭代似乎是错误的,但是不确定如何进行模式匹配。

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.

推荐答案

使用和:

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 是动态的,则可能。如果是静态列表,则可以使用模式匹配:

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

这篇关于确定地图是否具有某些键的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 01:14