[erlang-questions] pattern match test operator
Matthew Dempsky
matthew@REDACTED
Mon Nov 19 23:38:39 CET 2007
On 11/19/07, Andras Georgy Bekes <bekesa@REDACTED> wrote:
> [ X || X <- ListOrQLCTable,
> PATTERN1 ~= X orelse PATTERN2 ~= X]
Below you'll find a module that adds a parse transform so you can
write expressions like '~'(Pattern = X) or match(Pattern = X).
A quick example:
-module(test).
-compile({parse_transform, {match, '~'}}).
-export([foo/1]).
foo(X) -> '~'({burlap, _} = X).
While writing this module, I discovered that the Erlang compiler does
not allow parameterized modules and submitted a patch for it here:
http://article.gmane.org/gmane.comp.lang.erlang.patches/192
If you don't want to patch compile.erl (or can't), change the compile
line above to -compile({parse_transform, match}), the module line
below to -module(match), and change Name in the case clause to '~'.
-module(match, [Name]).
-export([parse_transform/2]).
parse_transform(Forms, _Options) ->
erl_syntax:revert_forms(
[erl_syntax_lib:map(fun doit/1, Form) || Form <- Forms]).
doit(Form) ->
%% Want to transform Name(Pattern = Body) to case Body of Pattern
%% -> true; _ -> false end.
case erl_syntax:type(Form) of
application ->
Operator = erl_syntax:application_operator(Form),
case erl_syntax:type(Operator) of
atom ->
case erl_syntax:atom_value(Operator) of
Name ->
[Args] = erl_syntax:application_arguments(Form),
match_expr = erl_syntax:type(Args),
Pattern = erl_syntax:match_expr_pattern(Args),
Body = erl_syntax:match_expr_body(Args),
erl_syntax:case_expr(
Body,
[erl_syntax:clause([Pattern],
none,
[erl_syntax:atom(true)]),
erl_syntax:clause([erl_syntax:underscore()],
none,
[erl_syntax:atom(false)])]);
_ ->
Form
end;
_ ->
Form
end;
_ ->
Form
end.
More information about the erlang-questions
mailing list