Erlang 模式与别名匹配
是否有可能在函数定义中匹配元组的某些子集,并且仍然在方法中获得完整的元组?
我想做的是这样的:
myfun({ foo, Bar }: Var) -> otherfunction(Var, stuff).
而不是:
myfun({ foo, Bar }) -> otherfunction({ foo, Bar }, stuff).
我希望这足够清楚。
谢谢。
is there a possibility to match in a function definition do some subset of a touple and still get get complete touple in the method ?
What I would like to do is something like this:
myfun({ foo, Bar }: Var) -> otherfunction(Var, stuff).
instead of:
myfun({ foo, Bar }) -> otherfunction({ foo, Bar }, stuff).
I hope this is clear enough.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过在前面添加下划线来忽略某些参数。例如
myfun( {foo, _Bar, Var } )
将通过忽略 _Bar 参数来匹配。这就是你的想法吗?
或者您的意思是:
myfun( {foo, Bar} = Var ) ->; otherfun( Var ).
在这种情况下,如果与 myfun 匹配成功,则 Var 将在 otherfun 中使用。原因是:Var 在表达式求值时未绑定,因此将被分配给 {foo, Bar}。
You can ignore some parameters by putting an underscore in front. E.g.
myfun( {foo, _Bar, Var } )
will match by ignoring the _Bar parameter. Is that what you had in mind?
Or did you mean:
myfun( {foo, Bar} = Var ) -> otherfun( Var ).
in this case, Var will be used in otherfun iff the match with myfun succeeded. The reason is: Var is un-bound at the time of evaluation of the expression and thus will be assigned to {foo, Bar}.
也许这就是你的意思:
这样,你就可以将你的函数导出为 myfun/1 (一个参数)。它只会匹配具有两个元素的元组。第一个必须是“foo”原子,而第二个可以是任何东西。在所有其他情况下,您都会得到一个函数子句,除非您为该函数指定不同的子句。例如,这样写是有意义的:
不过,我不完全确定这就是您所要求的。请告诉我这是否有帮助。
Maybe this is what you meant:
In this way, you can export your function as myfun/1 (one parameter). It will match just on tuples with two elements. The first one must be the "foo" atom, while the second can be anything. You will get a function clause in all other cases, unless you specify different clauses for the function. For example, it would make sense to have:
I'm not completely sure this is what you're asking, though. Please, let me know if this helped.
如果我的说法正确,那么您想要的是设置
Var
,仅包含一个匹配的{ foo, Bar }
,而无需执行任何额外的检查,例如简洁的缘故。据我所知,你不能在 Erlang 中做到这一点。对不起。 :)
If I have this correct, what you want is to have
Var
to be set, containing only a touple matching{ foo, Bar }
without having to do any additional checks, for conciseness sake.As far as I've ever seen, you can't do this in Erlang. Sorry. :)