[erlang-questions] List matching, help me make this look better

Kevin q2h46uw02@REDACTED
Sat Apr 25 19:28:04 CEST 2009


As an example I want to read a file, line by line, and pass the line 
into a function, and it want it to match
on the first 4 characters.  In the example I'm matching on "aaaa", 
"bbbb", "cccc".

Lines in the file would look like this
aaaa 123
bbbb 234
cccc 345
dddd 456
...


using the functions below works fine, as well as something similar using 
a case statement:

myfunc([$a, $a, $a, $a | _]) ->
    io:format("matched aaaa~n");

myfunc([$b, $b, $b, $b | _]) ->
    io:format("matched bbbb~n");

myfunc([$c, $c, $c, $c | _]) ->
    io:format("matched cccc~n");

myfunc(_) ->
    io:format("no matches~n").



My dissatisfaction is I'm taking the elegance of pattern matching in 
function params and making it ugly with
$a, $a, $a, $a.  Is there anyway to "explode" a list like "aaaa" 
(borrowing that term from ruby), or some other matching trick I'm missing??

Obviously ["aaaa"|_] won't work because its really just [ [$a, $a, $a, 
$a] | _ ]

One thing I tried was passing in a split tuple, but that feels more like 
a work-around
{"aaaa", _} = lists:split(4, "aaaa 1234").


I also tried converting everything to binaries but that traded ugly for 
ugly.



Thanks,
-kevin









More information about the erlang-questions mailing list