[erlang-questions] Code critique please

Sam Bobroff samb-bulk@REDACTED
Wed Dec 2 17:41:21 CET 2009


Jarrod Roberson wrote:
> is there anything that I can do to improve this code? Are the nested case of
> the best way to do that? It was the only thing I could get to work.
>   
Hi Jarrod,

I have another suggestion you might find interesting. I would like to 
factor out the recursion in the "is_subscribed" function because I think 
it's generally good to use comprehensions or folds if you can, instead 
of creating your own recursion. Unfortunately I can't see a way to do 
this trivially, so:

Given this code:
> % test to see if a dns_rr.domain is subscribed to
> is_subscribed(_,[]) -> false;
> is_subscribed(Dom,[S|Rest]) ->
>     case lists:suffix(S,Dom) of
>         true ->
>             {ok,S};
>         false ->
>             is_subscribed(Dom,Rest)
>     end.
I would first write a function like this:

%% first(Pred, List): Return either false or {true, Elem} where Elem is 
the first element of List for which Pred(Elem) returns true.
%% Pred must take one argument and return true or false.
first(Pred, []) ->
    false;
first(Pred, [X | Xs]) ->
    case Pred(X) of
        true ->
            {true, X};
        false ->
            first(Pred, Xs)
    end.

Then I could write is_subscribed like this:

is_subscribed(Dom, SS) ->
    first(fun(S) -> lists:suffix(S, Dom) end, SS).

This makes the "is_subscribed" function really easy to understand and 
provides "first" as a useful tool.

To be honest I was quite surprised that it wasn't in the "lists" 
module... maybe there is one somewhere I couldn't find.

Sam.




More information about the erlang-questions mailing list