micah
micah

Reputation: 8096

Programmatically Use Pattern Matching

Is it possible to programmatically pattern match?

Pattern = {error, '_'},
IsError = 
    case {error, "foo"} of
        Pattern -> true;
        _ -> false
    end.

I know I can do this with macros, but I have a dynamic list of patterns I would like to match that aren't known ahead of time.

Upvotes: 2

Views: 81

Answers (1)

legoscia
legoscia

Reputation: 41568

Perhaps the closest you can get is using a compiled match specification, by calling the functions ets:match_spec_compile and ets:match_spec_run:

MS = ets:match_spec_compile([{{error, '_'}, [], ['$_']}]).
Items = [ok, {error, foo}, {error, bar}].
ets:match_spec_run(Items, MS).

This returns the two items in the Items list that match:

[{error,foo},{error,bar}]

Upvotes: 2

Related Questions