2

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.

2
  • 1
    the question is kind of open, there are ways, but mostly depends on what you want to match and what patterns you have in mind, will you just match tuples? maps? any term at all? i.e. you can use something like Pattern Matching (5.7) (erlang.org/doc/apps/mnesia/mnesia_chap4) on mnesia, you still have to code it. yourself, but it is a known way of programmatically do pattern matching in erlang maybe some sample with the patterns you have in mind will help Commented Jul 8, 2022 at 18:06
  • @rorra Darn and it looks like that's specific to mnesia/ets/dets? Followed mensia:match_object all the way down to ets:match_object and that looks like a NIF so something I couldn't use outside of mnesia/ets/dets. github.com/erlang/otp/blob/master/lib/stdlib/src/ets.erl#L262 Commented Jul 11, 2022 at 14:40

1 Answer 1

2

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}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.