small erlang question.

WILLIAMS Dominic D.WILLIAMS@REDACTED
Fri Jan 16 11:44:10 CET 2004


> But better is:
> 
> case my_str(Text,[Str1,Str2,Str3]) of
>    1 -> do_1();
>    2 -> do_2();
>    3 -> do_3();
>    none -> ok
> end

Yes, I find that solution quite readable, but the OP
did ask how to do it *without* writing my_str/2...

Here a few solutions:

With a filter:

case lists:filter(
       fun(Str) ->
               0 /= string:str(Text,Str)
       end,
       [Str1,Str2,Str3]) of
    [Str1] ->
        ... ;
    [Str2] ->
        ... ;
    [Str3] ->
        ...
end.

Almost the same, but with a list comprehension:

case [Str || Str <- [Str1,Str2,Str3], string:str(Text,Str)>0] of
    [Str1] ->
        ...;
    [Str2] ->
        ...;
    [Str3] ->
        ...
end.

But here's my favourite:

Actions = [{Str1,fun(Txt) -> ... end},
           {Str2,fun(Txt) -> ... end},
           ...],
[Fun(Text) || {Str,Fun} <- Actions, string:str(Text,Str)>0].


Regards,

Dominic Williams.

----------------



More information about the erlang-questions mailing list