[erlang-questions] if-elseif-else trick

Raimo Niskanen raimo+erlang-questions@REDACTED
Mon Feb 18 15:21:32 CET 2019


On Mon, Feb 18, 2019 at 06:34:11PM +0900, zxq9@REDACTED wrote:
> On 2019年2月18日月曜日 9時02分11秒 JST Andreas Schultz wrote:
> > Hi Viktor,
> > 
: :
> > but why would you use such a thing when you can simply write:
> > 
> > if X > 0 -> pos;
> >    X < 0 -> neg;
> >    true -> zero
> > end.
> 
> 
> `if ... true` is a code stink.

That is a personal opinion.

if ... end selects the clause of the first succesful guard expression,
and 'true' is simply a succesful guard expression.

> Be explicit in your range tests -- that is what `if` is actually good at:
> 
>   if
>     X >  0 -> pos;
>     X <  0 -> neg;
>     X == 0 -> zero
>   end

That is a pretty example that is obviois about which cases it handles,
(note that it also handles non-numbers since all terms have an order)
but sometimes you instead want it to be obvious that you handle all cases.

    if
	is_integer(X), 0 =< X -> non_negative;
	true -> erlang:error(badarg)
    end

> 
> If you find yourself *needing* a `true` catchall, you should be writing a function head or `case`.

I have no problem using 'if' for that.  The 'true' catchall in 'if' is just
as much a catchall as the '_' catchall in 'case'.


> 
> 
> That said...
> The original premise of this thread is based on a misunderstanding of `if` and probably inexperience with `case`.

Agreed

> 
> 
> -Craig

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list