Erlang模式与别名匹配

ptr*_*ler 2 erlang pattern-matching

是否有可能在函数定义中匹配一些touple的子集并且仍然可以在方法中获得完整的功能?

我想做的是这样的事情:

myfun({ foo, Bar }: Var) -> otherfunction(Var, stuff).
Run Code Online (Sandbox Code Playgroud)

代替:

myfun({ foo, Bar }) -> otherfunction({ foo, Bar }, stuff).
Run Code Online (Sandbox Code Playgroud)

我希望这很清楚.

谢谢.

jld*_*ont 6

您可以通过在前面放置下划线来忽略某些参数.例如

myfun( {foo, _Bar, Var } )

将通过忽略_Bar参数进行匹配.那是你的想法吗?

或者你的意思是:

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

在这种情况下,如果与myfun的匹配成功,则将在otherfun中使用Var.原因是: Var在表达式的评估时是未绑定的,因此将被分配给{foo,Bar}.


Rob*_*loi 5

也许这就是你的意思:

myfun({foo, Bar } = Var) ->
  otherfunction(Var, stuff).
Run Code Online (Sandbox Code Playgroud)

这样,您可以将函数导出为myfun/1(一个参数).它只会在元组上与两个元素匹配.第一个必须是"foo"原子,而第二个可以是任何东西.除非为函数指定不同的子句,否则在所有其他情况下都将获得一个函数子句.例如,有:

myfun({foo, Bar } = Var) ->
  otherfunction(Var, stuff);
myfun(Var) ->
  {error, bad_format}.
Run Code Online (Sandbox Code Playgroud)

不过,我不完全确定这是你所要求的.如果这有帮助,请告诉我.