October 2014
Intermediate to advanced
280 pages
7h 20m
English
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, ... |
Read now
Unlock full access