[erlang-questions] pattern match test operator
Andras Georgy Bekes
Fri Nov 16 21:07:05 CET 2007
I'm missing a pattern match test operator from Erlang. What I mean?
I think there should be a built-in operator, which requires a pattern on
the left-side and a value on the right side, and returns true or false,
depending on the success of the match.
The semantics of the operator could be the same as this macro:
case Value of
I think this is very useful in some situations, for example,
case Value1 of
case Value2 of
could be rewritten as
case ?MATCH(PATTERN1,Value1) andalso ?MATCH(PATTERN2,Value2) of
Using an 'if' instead of 'case' would be better, but it won't work
because the 'case' expression -- the result of ?MATCH/2 -- is not
In this case you can use the 'case' construct, but if you want to have a
fun(Arg) when ?MATCH(PATTERN1,Arg) or ?MATCH(PATTERN2,Arg) ->
you can't do anything.
So having a built-in operator (that can be used in guards) would be
useful, I think. Such built-in stuff could probably be more efficient
than the above macro.
Of course, this operator would never bind variables (just like the macro
above). Maybe it should not accept patterns containing variables other
than _ .
Besides this, there should be a similar built-in function-like construct
that's argument is a pattern and returns a function that returns true
if its argument matches its pattern, false otherwise.
This can be achieved by the following macro:
case X of
I can imagine many uses of such functions (lists:filter-ing, filtering
ets and mnesia tables with such fun's instead of match patterns or
match specifications, etc). If such a function is not generated by the
above macro but some more clever way, it could be at least as efficient
as match patterns, maybe similar to match specifications.
I'm writing this mail to start a discussion. I think these two language
constructs would be very useful, but maybe I'm wrong. So tell me any
reason why these constructs are not viable or not needed in Erlang.
If we don't find such reasons and we consider these useful, I'm eager to
propose an enhancement.
More information about the erlang-questions