[erlang-questions] Code critique please

Bengt Kleberg bengt.kleberg@REDACTED
Wed Dec 2 18:03:26 CET 2009


Greetings,

Perhaps lists:dropwhile/2 can be used instead of first/2 ?


bengt

On Wed, 2009-12-02 at 11:41 -0500, Sam Bobroff wrote:
> 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.
> 
> 
> 
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
> 



More information about the erlang-questions mailing list