[erlang-questions] How do I elegantly check many conditions?

Richard Carlsson richardc@REDACTED
Wed Mar 25 15:35:09 CET 2009


Hynek Vychodil wrote:
> If I have function like
> 
> is_new_email(Email) ->
>  case mnesia:dirty_read(email, Email) of
>    []    -> ok;
>    _Else -> email_in_use
>  end.
> 
> I can choose if use it as
> 
> case is_new_email(Email) of
>   ok -> do_something();
>   email_in_use -> do_something_other()
> end
> 
> or as
> 
> ok = is_new_email(Email);
> 
> When You trow exception, I can't choose.

Of course you can choose. If you have:

  check_new_email(Email) ->
    case mnesia:dirty_read(email, Email) of
      []    -> ok;
      _Else -> throw(email_in_use)
    end.

you can use it as

  try check_new_email(Email) of
    ok -> do_something()
  catch
    email_in_use -> do_something_other()
  end

or as

  check_new_email(Email)

One advantage of this variant is that if the exception falls
through, you can find out that it was thrown from new_email()
rather than just seeing a badmatch in the calling function.

That doesn't mean that I'd use exceptions for the OP's
original question. Maybe, but not necessarily.

    /Richard




More information about the erlang-questions mailing list