O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing an if Statement

Let’s imagine Elixir didn’t have an if statement—all it has is case. Although we’re prepared to abandon our old friend the while loop, not having an if statement is just too much to bear, so we set about implementing one.

We’ll want to call it using something like

 
myif condition do
 
evaluate if true
 
else
 
evaluate if false
 
end

We know that blocks in Elixir are converted into keyword parameters, so this is equivalent to

 
myif condition,
 
do: evaluate if true,
 
else: evaluate if false

Here’s a sample call:

 
My.myif 1==2, ​do​: (IO.puts ​"1 == 2"​), ​else​: (IO.puts ​"1 != 2"​)

Let’s try to implement myif as a function:

 
defmodule​ My ​do
 
def​ myif(condition, clauses) ​do
 
do_clause = Keyword.get(clauses, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required