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.
It's possible. Here is how: https://github.com/zuiderkwast/elseif
Disclaimer: This may be considered macro and parse-transform abuse. You
may get strange syntax error messages if e.g. using ?elseif without
?'if' or if leaving out the mandatory ?else part.
Viktor
_______________________________________________
erlang-questions mailing list
erlang-q...@erlang.org
http://erlang.org/mailman/listinfo/erlang-questions
`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
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
So you've reimplemented LISP's COND. Please just do it properly in
the Erlang parser (I belive 'cond' is already a reserved word), and
write an EEP for it.
FWIW, my code tends to be CASE heavy largely to avoid the inherent
problems of Erlang's limited guard expressions and butt-ugly "if".
-define(true,else).
yielding ?else ->
is much of an improvement.
Why not just allow the keyword else as a synonym for true when its usage
would improve the readability? (At times, "true" reminds me of trying to
read (SAT-like) sentences like: "Whenever he couldn't think of whether
or not he might have forgotten to turn the light on or off, or not.")
Why not just use `if` where it fits semantically?
These periodic discussions of how to use silly cheats to avoid proper
code layout always puzzle me.
-Craig
Worth extracting as its own quote.