views:

128

answers:

3

Hi, 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.

+5  A: 

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.

Roberto Aloi
+6  A: 

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

jldupont
"ignoring the _Bar parameter" is not strictly correct. The variable _Bar will be bound to the second element of the tuple and can be used as any normal variable. As the _Bar starts with an _ the compiler will not warn about it not being used. Apart from this _Bar behaves as a normal variable and can be used as one.
rvirding
@rvirding: yes, thanks for the enhanced wording.
jldupont
A: 

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. :)

scott_karana
you are wrong: check your answer again.
jldupont
This is incorrect. As the two other posts indicate you can indeed do what he is asking.
Jeremy Wall