官术网_书友最值得收藏!

Pattern matching on maps

To use pattern matching on a map, we set our pattern with the key-value pairs we want to match on, as you can see in the following example:

iex> %{"name" => name, "age" => age} = %{"name" => "Gabriel", "age" => 1}
%{"age" => 1, "name" => "Gabriel"}
iex> name
"Gabriel"
iex> age
1

Note that in this case we're matching on all keys of the map, but this isn't necessarywe could just match on age, for instance. However, your pattern may only contain keys that exist on the map that's being matched on, otherwise MatchError will be raised.

Sometimes, you may want to match on the value of a variable, instead of rebinding it to a new value. To this end, you can use the pin operator, represented by the ^ character:

iex> name = "Gabriel"
"Gabriel"
iex> %{name: ^name, age: age} = %{name: "Gabriel", age: 1}
%{age: 1, name: "Gabriel"}
iex> %{name: ^name, age: age} = %{name: "Jose", age: 1}
** (MatchError) no match of right hand side value: %{age: 1, name: "Jose"}

As we can see in the preceding snippet, we have the name variable bound to "Gabriel". We then match a map as we did previously in this section, this time using the contents of the name variable. This is equivalent to using the "Gabriel" literal on the left-hand side. When we're trying to match against a map that has a value different than that of the pinned variable, we get a MatchError, as expected.

When working with the pin operator, the variable you're using must already be bound, as it will not bind the variable in case it doesn't exist. If you use the pin operator on a non-existent variable, you'll get a CompileError stating that the variable you're trying to use is unbound.
主站蜘蛛池模板: 延边| 呼图壁县| 玉环县| 徐闻县| 芜湖市| 离岛区| 柳州市| 扬州市| 临洮县| 揭阳市| 泊头市| 凤城市| 永丰县| 竹溪县| 江川县| 鹿泉市| 海安县| 盖州市| 巴彦淖尔市| 清丰县| 万荣县| 鄂伦春自治旗| 阿拉善盟| 通化市| 孝义市| 田阳县| 嘉祥县| 山西省| 桂东县| 宜良县| 扬州市| 临武县| 昭平县| 梁平县| 方山县| 临漳县| 龙泉市| 湘阴县| 大余县| 马公市| 武宣县|