pillaiindu

pillaiindu

Why in the cond we must use true as the final condition? Why can't we use _?

For example the following,

iex(16)> cond do
...(16)>  2 + 2 == 5 ->
...(16)>   "Not true"
...(16)>  2 * 2 == 3 ->
...(16)>   "nor this"
...(16)>  _ -> 
...(16)>   "will match"
...(16)> end
** (CompileError) iex:21: invalid use of _ inside "cond". If you want the last clause to always
 match, you probably meant to use: true ->

Most Liked

Ted

Ted

I think this is worth reiterating:

For example, Clojure’s cond works in similar fashion, although the convention there is to use :else instead of true, e.g.,:

(let [x 11]
  (cond
    (< x 2)  "x is less than 2"
    (< x 10) "x is less than 10"
    :else  "x is greater than or equal to 10"))

https://clojure.org/guides/learn/flow#_cond

And :else also works in Elixir:

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.

peerreynders

peerreynders

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.

Why can’t we use _?

cond by design

Raises an error if all conditions evaluate to nil or false .

so

it may be necessary to add a final always-truthy condition (anything non- false and non- nil )

_ would imply that any value is OK.

In the end it makes the design of cond simpler
(in the true sense of the word - if ... else if ... else .. end is more familiar).

true -> expression

is no different from the other

condition -> expression

before it - i.e. there is no need for a special else part inside cond.

NobbZ

NobbZ

Beacause _ is only valid in a match and cond is only expanding to a bunch of nested ifs.

Qqwy

Qqwy

TypeCheck Core Team

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 :_ :stuck_out_tongue_winking_eye:. don’t do this please

DevotionGeo

DevotionGeo

In other words you’re not matching something, but are checking which statement is true.

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New

We're in Beta

About us Mission Statement