Is there a way to create first-class-like patterns in Erlang? I need to be able to create and pass patterns as args to other functions but I know patterns are not first class in Erlang. I also looked at Elixir but it doesn't seem to offer anything more as far as patterns go.
I was wondering if anyone has come up with a simple solution to this problem. I was thinking of trying to implement something like this:
% Instead of using variables, we would just use uppercase atoms which would serve as vars
% A passable pattern
Pattern = {ok, 'Result'}.
% Custom function to check for matches
match(pattern, {ok, [1,2,3]}). % => true
I am new to Erlang so perhaps this is completely unnecessary. Perhaps there is a library that does this sort of thing?
Any advice is greatly appreciated. Thanks in advance!
I don't know if something exists already that does what you want, but you can easily implement it like this:
-module (match).
-compile([export_all]).
-define(MF(S), fun(S) -> true; (_)->false end).
match(F,V) -> F(V).
test() ->
Pattern = ?MF({ok,_}),
false = match(Pattern,{error,reason}),
true = match(Pattern,{ok,[1,2,3]}).