elt547
Why can or be used in guard clauses but not ||?
Curious as to why this is not permitted. I suspect it has something to do with or only accepting a boolean as the first operand. But why does this matter with guard clauses?
Most Liked
hst337
because left || right actually compiles to something like
case left do
v when v == false or v == nil -> right
_ -> left
end
Which is not allowed in guards
hst337
Only || and && are not allowed in guards. All other boolean operators are allowed
benwilson512
Yeah && and || have what is called a “short circuit” behavior where they will only evaluate the right hand side of the operand if they need to. This allows you to do things like:
value = params[:some_opt_key] || raise "this parameter is required!
If the left hand side is “truthy” then || short circuits and doesn’t evaluate the raise at all. This sort of branching behavior doesn’t even make sense in guards.
christhekeele
Worth noting that in guards, or is precisely the same as calling :erlang.orelse/2.
This might work for literals, but I’m not sure it works for arbitrary expressions—in general, nor successful at not evaluating the second branch.
In general there’s not much reason to want || in these cases, as we are not working with arbitrary expressions—we know that functions allowed in guards are always idempotent, and don’t have side effects, so there’s little gain in suppressing them!
lud
This is because orelse will just err with badarg, whereas in Elixir we want more accurate errors. But besides that this is the same behaviour as orelse : only booleans on the left.







