Tuesday Nov 13, 2007

Regexp Syntax in Pattern Match?

Pattern match in Erlang is very useful, but it has some limits, for example, to match something like:

\d\d\dx/\d\d\d\d/\d\d/\d\d/

I have to write the code as:

<<_:S/binary, C1,C2,C3,$x,$/,Y1,Y2,Y3,Y4,$/,M1,M2,$/,D1,D2,$/,_/binary>> when
     C1 > 47, C1 < 58, C2 > 47, C2 < 58, C3 > 47, C3 < 58,
     Y1 > 47, Y1 < 58, Y2 > 47, Y2 < 58, Y3 > 47, Y3 < 58, Y4 > 47, Y4 < 58,
     M1 > 47, M1 < 58, M2 > 47, M2 < 58, D1 > 47, D2 < 58, D2 > 47, D2 < 58

But life can be simple, by using parse_transform, we can write above code to:

<<_:S/binary,d,d,d,$x,$/,d,d,d,d,$/,d,d,$/,d,d,$/,_/binary>>

Where d is digital. The parse_trasnform can process the AST tree to make the true code.

And more, since current erl_parse supports any atom in binary skeleton, we can write pattern match as:

<<_:S/binary,'[a-z]','[^abc]','var[0-9]',$x,$/,d,d,d,d,$/,d,d,$/,d,d,$/,_/binary>>

Will somebody write such a parse_transform?

Comments:

Post a Comment:
Comments are closed for this entry.