Google Groups

programmatically matching erlang terms


stefo Feb 20, 2011 4:54 AM
Posted in group: erlangcamp
Hi, greetings from Switzerland

my diameter protocol parser transforms billing request variables into
lists of tuples with a builtin hierarchy.
an example for one such element in the list:

{'Subscription-Id', [
                       {'Subscription-Id-Type',0}
                       ,{'Subscription-Id-Data',"41793952345"}
                      ]
 }

how can I have a match function on these tuples, similar to what
ets:match/2 uses but on a given term instead of an ets table? It would
have to support the '_' placeholder for any erlang term.

in other words: has anyone a good and fast implementation for my
function avps_match() in the test case below?

Thanks alot

Stefan

avps_match(Pattern, Tuple) ->
        %% implemetation of match function similar
        %% to ets:match needed here on single term Tuple
        false.

avps_match_test() ->
        %% success matchings without placeholders
        ?assert(avps_match({a,17}, {a,17}) =:= true),
        ?assert(avps_match({a,"45"}, {a,"45"}) =:= true),
        ?assert(avps_match({a,[{b,0},{c,"45"}]}, {a,[{b,0},{c,"45"}]}) =:=
true),
        %% failed matchings without placeholders
        ?assert(avps_match({a,17}, {a,18}) =:= false),
        ?assert(avps_match({a,"45"}, {a,"46"}) =:= false),
        ?assert(avps_match({a,"45"}, {a,17}) =:= false),
        ?assert(avps_match({a,"45"}, {b,"45"}) =:= false),
        ?assert(avps_match({a,[{b,0},{c,"45"}]}, {a,[{b,0},{c,"46"}]}) =:=
false),
        ?assert(avps_match({a,[{b,0},{c,"45"}]}, {a,[{b,1},{c,"45"}]}) =:=
false),
        ?assert(avps_match({a,[{b,0},{c,"45"}]}, {a,[{x,0},{c,"45"}]}) =:=
false),
        ?assert(avps_match({a,[{b,0},{c,"45"}]}, {x,[{b,0},{c,"45"}]}) =:=
false),
        %% success matchings with '_' placeholders
        ?assert(avps_match({a,'_'}, {a,"45"}) =:= true),
        ?assert(avps_match({a,[{b,0},{c,'_'}]}, {a,[{b,0},{c,"45"}]}) =:=
true),
        ?assert(avps_match({a,'_'}, {a,[{b,0},{c,"45"}]}) =:= true),
        ?assert(avps_match({a,[{b,'_'},{c,"45"}]}, {a,[{b,0},{c,"45"}]}) =:=
true),
        ?assert(avps_match({a,[{b,'_'},{c,'_'}]}, {a,[{b,0},{c,"45"}]}) =:=
true),
        %% failed matchings with '_' placeholders
        ?assert(avps_match({a,[{b,0},{c,'_'}]}, {a,[{b,0},{x,"45"}]}) =:=
false),
        ?assert(avps_match({a,[{b,0},{c,'_'}]}, {a,[{b,1},{c,"45"}]}) =:=
false),
        ?assert(avps_match({a,[{b,0},{c,'_'}]}, {x,[{b,0},{c,"45"}]}) =:=
false),
        ?assert(avps_match({a,[{b,'_'},{c,"45"}]}, {x,[{b,0},{c,"45"}]}) =:=
false),
        ok.