Erlang 模式与别名匹配

发布于 2024-08-10 21:58:39 字数 277 浏览 4 评论 0原文

是否有可能在函数定义中匹配元组的某些子集,并且仍然在方法中获得完整的元组?

我想做的是这样的:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜尕妞 2024-08-17 21:58:39

您可以通过在前面添加下划线来忽略某些参数。例如

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}.

携余温的黄昏 2024-08-17 21:58:39

也许这就是你的意思:

myfun({foo, Bar } = Var) ->
  otherfunction(Var, stuff).

这样,你就可以将你的函数导出为 myfun/1 (一个参数)。它只会匹配具有两个元素的元组。第一个必须是“foo”原子,而第二个可以是任何东西。在所有其他情况下,您都会得到一个函数子句,除非您为该函数指定不同的子句。例如,这样写是有意义的:

myfun({foo, Bar } = Var) ->
  otherfunction(Var, stuff);
myfun(Var) ->
  {error, bad_format}.

不过,我不完全确定这就是您所要求的。请告诉我这是否有帮助。

Maybe this is what you meant:

myfun({foo, Bar } = Var) ->
  otherfunction(Var, stuff).

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:

myfun({foo, Bar } = Var) ->
  otherfunction(Var, stuff);
myfun(Var) ->
  {error, bad_format}.

I'm not completely sure this is what you're asking, though. Please, let me know if this helped.

西瑶 2024-08-17 21:58:39

如果我的说法正确,那么您想要的是设置 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. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文