[erlang-questions] if-elseif-else trick

zxq9@REDACTED zxq9@REDACTED
Mon Feb 18 10:34:11 CET 2019


On 2019年2月18日月曜日 9時02分11秒 JST Andreas Schultz wrote:
> Hi Viktor,
> 
> Viktor Söderqvist <viktor@REDACTED> schrieb am Sa., 16. Feb. 2019 um
> 19:24 Uhr:
> 
> > Hey list!
> >
> > Last night I was thinking that it might be possible to implement
> > if-elseif-else syntax using macros and a parse transform, so you can
> > write like this:
> >
> > -include_lib("elseif/include/elseif.hrl").
> >
> > f(X) ->
> >     ?'if'(X > 0)   -> pos
> >     ?elseif(X < 0) -> neg
> >     ?else          -> zero
> >     end.
> >
> 
> 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.
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

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


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


-Craig



More information about the erlang-questions mailing list