<div dir="ltr">This makes much more sense now :) Just noting that Elixir has the `cond` expression for this use case.<br></div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Tue, Feb 19, 2019 at 8:37 AM Viktor Söderqvist <<a href="mailto:viktor@zuiderkwast.se">viktor@zuiderkwast.se</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">Hi!<br>
<br>
My example proved silly. Of course, normal 'if' is fine for guard<br>
expressions and catch-all is to be avoided in general. I agree.<br>
<br>
What I failed to mention was that you can use non-guard expressions with<br>
this trick. (The trick's actually rewriting the elseifs to nested case.)<br>
<br>
When using if with non-guard expressions, you need to evaluate them in<br>
advance, which you may not want if these are side-effectful or just slow:<br>
<br>
f() -><br>
Cond1 = g1(),<br>
Cond2 = g2(),<br>
Cond3 = g3(),<br>
if Cond1 -> a;<br>
Cond2 -> b;<br>
Cond3 -> c;<br>
true -> d<br>
end.<br>
<br>
Therefore, you often see nested case expressions instead:<br>
<br>
f() -><br>
case g1() of<br>
true -> a;<br>
false -><br>
case g2() of<br>
true -> b;<br>
false -><br>
case g3() of<br>
true -> c;<br>
false -> d<br>
end<br>
end<br>
end.<br>
<br>
... or broken down into multiple functions:<br>
<br>
f() -><br>
case g1() of<br>
true -> a;<br>
false -> f2()<br>
end.<br>
f2() -><br>
%% You know<br>
<br>
There's the throw style too, a slightly silly but a flat style:<br>
<br>
f() -><br>
try<br>
g1() andalso throw(a);<br>
g2() andalso throw(b);<br>
g3() andalso throw(c);<br>
d<br>
catch<br>
X -> X<br>
end.<br>
<br>
The point of the ?elseif syntax trick is that it lets you write the<br>
nested case above as the flat structure:<br>
<br>
f() -><br>
?'if'(g1()) -> a;<br>
?elseif(g2()) -> b;<br>
?elseif(g3()) -> c;<br>
?else -> d.<br>
<br>
You can even bind variables in the conditions if you would want that,<br>
just to avoid deeply nested code. I would look more like perl than<br>
erlang though, so don't do that.<br>
<br>
>> That said...<br>
>> The original premise of this thread is based on a misunderstanding of `if` and probably inexperience with `case`.<br>
> <br>
> Agreed<br>
> <br>
<br>
I agree too. :-) Thanks for clarifying!<br>
<br>
Btw, I'm sorry for posting without having a real question. I just wanted<br>
to show what can be done using a non-trivial parse transform.<br>
<br>
Viktor<br>
_______________________________________________<br>
erlang-questions mailing list<br>
<a href="mailto:erlang-questions@erlang.org" target="_blank">erlang-questions@erlang.org</a><br>
<a href="http://erlang.org/mailman/listinfo/erlang-questions" rel="noreferrer" target="_blank">http://erlang.org/mailman/listinfo/erlang-questions</a><br>
</blockquote></div>