I had to post this, mainly for the entertainment value but also as a reminder to myself not to start playing with new stuff after a long hard day of ‘real’ development. I just needed a quick bit of code that starts out with a string of the form “inc=45,56,76,102&exc=10,11,15,98″ and spits out two lists of integers. I somehow ended up with this:
% On entry, A#arg.querydata is a string of the form "inc=n,n,n&exc=n,n,n
QueryArgs=string:tokens(A#arg.querydata,"&"),
QueryArgs2=lists:map(fun(T) -> string:tokens(T,"=") end,QueryArgs),
[[_|IncP]|_]=lists:filter(fun(T) -> [N|_Rest]=T,"inc"==N end,QueryArgs2),
[[_|ExcP]|_]=lists:filter(fun(T) -> [N|_Rest]=T,"exc"==N end,QueryArgs2),
IncS=string:tokens(lists:nth(1,IncP),","),
ExcS=string:tokens(lists:nth(1,ExcP),","),
Includes=lists:map(fun(T)->list_to_integer(T) end,IncS),
Excludes=lists:map(fun(T)->list_to_integer(T) end,ExcS).
% On exit, Includes=[n1,n2,...] and Excludes=[n1,n2,...]
Just as shocking as the code are the facts that a) it took me half an hour to make it work, and b) it actually works at all. Worse still, I don’t even need the code, since ultimately it will all be handled via JSON-RPC and not some nasty ad-hoc HTTP query processing - I just wanted to do a quick test in the meantime. The mission was accomplished, but surely there’s a far more elegant way to do the above. Unfortunately, I’m not going to find it today. I will be compelled to come back to it of course, and when I do I hope I can keep the lovely [[_|IncP]|_] part.