功能头中的地图图案匹配 [英] Map pattern matching in function head

查看:73
本文介绍了功能头中的地图图案匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数接受两个参数,一个由三个元素组成的元组,以及一个将在元组值中分配最后两个元素的映射.因此,例如,我将调用这样的函数

I'm trying to make a function that accepts two arguments, a tuple consisting of three elements, and a map that will assign the last two elements in the tuple values. so for example I would call the function like this

modulename:funcName({description, a,b}, #{a=>1, b=>2)).

我无法使模式匹配正常工作.我的功能看起来像这样

I cannot get the pattern matching to work. My function as it is looks like this

funcName({description,a,b}, #{a:=A, b:=2}.

我无法使元组中的原子映射到映射中的值.我该怎么办.

I cannot get the atoms in the tuple to be mapped to the value in the map. How do I go about this.

推荐答案

如果我正确理解了您想要的内容,则无法在函数头本身中执行此操作,因为用作映射键的所有变量必须事先绑定.来自 OTP 23精彩博客文章:

If I understand what you want correctly, this isn't possible to do in the function head itself, because all variables used as map keys must be previously bound. From the OTP 23 highlights blog post:

下面有一个非法示例,表明仍然不支持将未绑定变量用作键模式表达式的一部分.在这种情况下,键是不受约束的,并且要求键表达式中使用的所有变量必须预先绑定.

Below there is an illegal example showing that it is still not supported to use an unbound variable as part of the expression for the key-pattern. In this case Key is not bound and the requirement is that all variables used in a key expression must be previously bound.

illegal_example(Key, #{Key := Value}) -> Value.

因此,您必须编写如下内容:

So you'd have to write something like this:

func_name({description, Key1, Key2}, Map = #{}) ->
    #{Key1 := Value1, Key2 := Value2} = Map,
    ....

之所以可行,是因为在第二行上,变量 Key1 Key2 已经绑定,因此可以用来匹配映射中相应键的值

This works because on the second line the variables Key1 and Key2 are already bound, so they can be used to match out the values of the corresponding keys in the map.

或者,使用 maps:get 获得相同的结果:

Alternatively, use maps:get to achieve the same result:

func_name({description, Key1, Key2}, Map = #{}) ->
    Value1 = maps:get(Key1, Map),
    Value2 = maps:get(Key2, Map),
    ....

这篇关于功能头中的地图图案匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆