If Else in Elixir
Branching with if
and else
in Elixir is straightforward.
defmodule IfElseExample do
def run do
# Here's a basic example.
if rem(7, 2) == 0 do
IO.puts("7 is even")
else
IO.puts("7 is odd")
end
# You can have an `if` statement without an else.
if rem(8, 4) == 0 do
IO.puts("8 is divisible by 4")
end
# Logical operators like `and` and `or` are often useful in conditions.
if rem(8, 2) == 0 or rem(7, 2) == 0 do
IO.puts("either 8 or 7 are even")
end
# A variable can be assigned within the condition;
# it will be available in all branches.
num = 9
cond do
num < 0 -> IO.puts("#{num} is negative")
num < 10 -> IO.puts("#{num} has 1 digit")
true -> IO.puts("#{num} has multiple digits")
end
end
end
IfElseExample.run()
Note that in Elixir, you don’t need parentheses around conditions, but the do
and end
keywords are required to define the block.
To run the program:
$ elixir if_else_example.exs
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
In Elixir, there’s no direct equivalent to Go’s ability to declare a variable in an if statement. Instead, we typically assign the variable before the conditional structure.
Also, Elixir doesn’t have a direct else if
construct. For multiple conditions, it’s common to use cond
as shown in the last example. Alternatively, you can nest if
statements or use pattern matching with case
.
Elixir also provides a ternary-like operator with the if
macro:
result = if condition, do: value1, else: value2
This can be useful for simple conditional assignments.