I understand that you are only referring to a mental model - but as you know in Elixir a literal if is actually implemented a case expression, while cond is it’s own special form (so if taken literally this could be confusing).
Essentially the first expression that evaluates to a truthy value “wins” and consequently the expression to the right of that -> is evaluated and becomes the value of the cond expression. In a sense the cond expression is enclosing a sequence of condition -> expression constructs.
cond do
x > 0 -> :true
x < 0 -> :false
_ -> :wrong
end
Conceptually compiles to:
case [] do
_ when x > 0 -> :true
_ when x < 0 -> :false
_ when _ -> :wrong
end
You can’t have a _ in a guard, and cond is like guards (except you can call any function, linearly run, etc… etc… unlike cases). _ is used for matching, and nothing is being matched.
However, you don’t need to use true, you just need to use anything that is not the atoms :false or :nil, so you can use :else -> etc... or :blah -> etc... or 42 -> etc... or whatever.
As far as I’m aware those restrictions do not apply to cond conditions.
(except you can call any function, linearly run, etc… etc… unlike case s).
It’s one of those things that took me by surprise with Erlang’s ifexpression because it’s based on guard expressions which severely restricts the type of conditions you can use.
Yep, I like Erlang’s if as it is simple and easy to reason about without any weird and surprising speed costs. I think cond compiles down to a case tree or something like that in core erlang? I need to check again…
iex(6)> x = 11
11
iex(7)> cond do
...(7)> x < 2 -> "x is less than 2"
...(7)> x < 10 -> "x is less than 10"
...(7)> :else -> "x is greater than or equal to 10"
...(7)> end
"x is greater than or equal to 10"
true, :else, "default", etc. are all truthy and therefore serve the purpose.
Personally, I kinda like :else -> or :default -> but the Elixir community appears to have settled on true -> so I’ll use that.
If you want to get really fancy with it and make sure that nobody else will understand your code any more, you could even use :_ . don’t do this please