[erlang-questions] Re: try catch scope

Raimo Niskanen raimo+erlang-questions@REDACTED
Wed Jun 30 16:17:31 CEST 2010


On Wed, Jun 30, 2010 at 07:33:39AM -0600, Wes James wrote:
> Mangus,
> 
> Thanks! This is much better!
> 
> has_query(A) ->
> 	try
> 		yaws_api:parse_query(A) /= []
> 	catch
> 		_:_ -> false
> 	end.
> 
> -wes

This might be even clearer (separating the right and wrong cases):

has_query(A) ->
    try yaws_api:parse_query(A) of
        [] -> false;
        _ -> true % Were you supposed to return true for this case?
    catch
        error:_ -> false % Only cathes runtime errors, not exit/1.
    end.

> 
> On Wed, Jun 30, 2010 at 5:53 AM, Magnus Henoch
> <magnus@REDACTED> wrote:
> > Wes James <comptekki@REDACTED> writes:
> >
> >> has_query(A) ->
> >>               case length(yaws_api:parse_query(A)) of
> >>                       0  -> false;
> >>                       _ -> true
> >>               end.
> >
> > A separate note about the code: you should avoid "case length(Foo)" when
> > possible, since length/1 needs to traverse the entire list.  Just
> > comparing the result to the empty list is probably faster:
> >
> > case yaws_api:parse_query(A) of
> >    [] -> false;
> >    _ -> true
> > end.
> >
> > And this can be simplified further:
> >
> > yaws_api:parse_query(A) /= [].
> >
> > (There is a difference between my two examples and yours: your code will
> > crash with badarg if the result is not a proper list, while mine will
> > just return false.)
> >
> > --
> > Magnus Henoch, magnus@REDACTED
> > Erlang Solutions
> > http://www.erlang-solutions.com/
> >
> > ________________________________________________________________
> > erlang-questions (at) erlang.org mailing list.
> > See http://www.erlang.org/faq.html
> > To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
> >
> >
> 
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
> 

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB


More information about the erlang-questions mailing list