citxx
citxx

Reputation: 2545

Erlang - pattern matching predicate

To know if particular expression matches specified pattern I can write in erlang something like following:

case <expression> of
    <pattern> -> true;
    _ -> false
end

For example:

case {1, 2, 3} of
    {_, 2, _} -> true;
    _ -> false
end

Is there a way to write it in more compact way? Something like:

is_match(<pattern>, <expression>)

Upvotes: 1

Views: 390

Answers (2)

Pascal
Pascal

Reputation: 14042

another macro :o) -define (IS_MATCH(PAT,EXP), catch(PAT = EXP) == EXP end). with no case, but I am not sure that a catch is better.

Upvotes: 0

RichardC
RichardC

Reputation: 10567

No, there's no such construct. You could define a macro to do it:

-define(is_match(Pattern, Expr), case Expr of Pattern -> true; _ -> false end).

Upvotes: 8

Related Questions