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

Kostis Sagonas kostis@REDACTED
Sat Apr 25 19:44:51 CEST 2009


Kevin wrote:
> 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??

Yes.  Write:

   myfunc("aaaa" ++ _) ->
       io:format("matched aaaa~n");

instead.  Works also as:

   myfunc("aaaa " ++ R) ->
       io:format("matthed aaaa~n"),
       io:format("R matches 123 in your example file");

Kostis



More information about the erlang-questions mailing list