Implementing an if Statement
Let’s imagine that Elixir didn’t have an if statement—that 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, ... |
Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.