[erlang-questions] pattern match test operator

Andras Georgy Bekes bekesa@REDACTED
Fri Nov 16 23:44:08 CET 2007


> Unless there is some use case I can't see right now, the constructs
> you are suggesting are not really needed.
Not needed: everything can be programmed without them, but sometimes in 
an ugly way.

> More precisely, I can't see when I would want to do a match against a
> pattern containing only '_'s and if that is true I wouldn't need to
> match again to retrieve some of the internal terms later on. In this
> case, it's better to match even the internal structure from the
> start.
For example, today I've seen a piece of code (in AXD301 sources) that 
looked like:

case Expr1 of
   PATTERN1 ->
      case Expr_with_side_effects of
         [[{_,0,_,_,}]] ->
         _ ->
   _ ->

The strange pattern above is real, other parts are changed of course.
Actually this was the reason I wrote this mail: we coudn't find any 
elegant solution.

My suggested (elegant) solution is:
case ?MATCH(PATTERN1,Expr1) andalso 
     ?MATCH([[{_,0,_,_,}]],Expr_with_side_effects) of
   true ->
   _ ->

Other example: The whole ets:match is about matching against a pattern 
containing only '_'s. But yes, you got the point: The patterns should 
be allowed to contain any variables, because having a variable more 
than once in a pattern is useful (this is why patterns for ets:match 
can contain '$1','$2'... stuff, but that's ugly).

> * One could rewrite
>   case Value1 of
>      PATTERN1 ->
>          case Value2 of
>              PATTERN2 ->
>                  this;
>              _ ->
>                  that
>          end;
>      _->
>          that
>   end
> as
>   case {Value1, Value2} of
>      {PATTERN1, PATTERN2} ->
>            this;
>      _->
>           that
>   end
Not acceptable. This evaluates Value2 unconditionally. The original 
evaluates it only if Value1 matches PATTERN1 (think about side effects 
and runtime). The names Value1 and Value2 were misleading. Think about 
Expr1, Expr2.

> * Regarding
>       fun(Arg) when ?MATCH(PATTERN1,Arg) or ?MATCH(PATTERN2,Arg) ->
> I'm not sure why you want to match Arg against two patterns.
I've seen a code fragment (in AXD301) several weeks ago, so I can't 
remember correctly, but: The function was supposed to select the first 
case if one argument looked like "R7A..." or "R12C...".
This could be done with my construct:

function(X) when ?MATCH("R7A"++_,X) or ?MATCH("R12C"++_,X) ->

As far as I remember the function supposed to crash if there's no match.

All the solutions we've found were ugly in some way.

> If you 
> meant fun(Arg1, Arg2) when ?MATCH(PATTERN1,Arg1) or
> ?MATCH(PATTERN2,Arg2) -> then the usual way to do that is
>       fun(PATTERN1, PATTERN2) ->
I didn't mean this. I meant a function head that matches if an argument 
matches (at least) one of several patterns.


More information about the erlang-questions mailing list