Conditions

if is the condition keyword of Elixir. It is an expression rather than a statement: the whole form returns a value, so a branch can assign a result as easily as it can print one. The condition follows the truthiness rule of the previous lesson, where only false and nil fail, and a test that asks for the negative case is written inside it with not or !.

if and else

if takes a condition, a do block and an optional else block, and closes with end. The condition is any expression; the branch that runs is the one whose side of the condition won:

age.exs

age = 20 if age >= 18 do IO.puts("adult") else IO.puts("minor") end

elixir age.exs

adult

The indentation is two spaces, and mix format keeps it. A one-line form exists for a short branch: if age >= 18, do: IO.puts("adult"). Both forms mean the same thing, and the formatter leaves the one-line form alone as long as it fits the line.

A negative test

When the negative case is the interesting one, the test goes inside if with not or its short form !. The two are one operator at two lengths, and both return the opposite of the truthiness of their argument, so a block that runs when nobody is logged in reads:

negate.exs

logged_in = false if not logged_in do IO.puts("the form is shown") end if !logged_in, do: IO.puts("the same test on one line")

elixir negate.exs

the form is shown
the same test on one line

unless was the keyword for this test in older code, and the projects you meet still carry it. The documentation of this version marks unless/2 as deprecated with the text Use if/2 instead, so new code writes the test inside if. The old form swaps the two branches of an if, and the same program written that way still runs:

old_unless.exs

logged_in = false unless logged_in do IO.puts("the form is shown") end

elixir old_unless.exs

the form is shown

The compiler prints no warning for it, which is why old code keeps working and the habit survives. Read it as if not logged_in and write the new form when the file is next touched. A negated condition inside unless, such as unless !logged_in, is where the form stops reading at all; Credo in strict mode reports it as NegatedConditionsInUnless. A negated test with an else has its own report, NegatedConditionsWithElse, and the fix in both cases is the positive test with the branches written the right way round.

A branch is a value

The value of an if is the value of the branch that ran, which makes a function that returns a label a single expression. There is no return and no variable declared before the branch:

gate.exs

defmodule Gate do def level(age) do if age >= 18 do :adult else :minor end end end IO.puts(Gate.level(20)) IO.puts(Gate.level(12))

elixir gate.exs

adult
minor

The last expression of the function body is the if, so the function returns the atom its branch produced. A branch may hold several expressions; the value of the branch is the value of its last expression, and a print in the middle is a side effect rather than the result.

The mistake: a branch that returns nil

An if with no else still has a value when the condition fails: nil. A program that assigns that value and then does arithmetic on it stops with an ArithmeticError, and the message shows the nil it got:

nil.exs

value = if false, do: 42 IO.puts(value + 1)

elixir nil.exs

** (ArithmeticError) bad argument in arithmetic expression: nil + 1
    :erlang.+(nil, 1)
    nil.exs:2: (file)

The fix is to give the if the branch that handles the failure, or to test the value before using it. A branch that is meant to produce a number should always produce one, and a program that returns nil by accident says so in the error rather than failing later. Matching a value against several patterns, and a chain of conditions, have their own lessons in the next chapter; case is the first of them.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an if expression return?

    Answer

    The value of the branch that ran

    Both keywords are expressions, so the whole form has the value of its branch.

  2. Which form is the current way to run a block only when x is false?

    Answer

    if !x do the block end

    A negative test goes inside if with not or !; unless is deprecated in this version.

  3. What is the value of if false, do: 42?

    Answer

    nil

    The do branch did not run and there is no else branch, so the form is nil.

  4. Which form is a shorter way to write a one-line if?

    Answer

    if age >= 18, do: IO.puts("adult")

    The keyword form takes do: with a single expression and needs no end.

  5. What does this program print? IO.puts(if true, do: "yes", else: "no")

    Answer

    yes

    The condition is true, so the do branch is the value and IO.puts/1 prints it.

  6. What does this program print? IO.puts(if nil, do: "yes", else: "no")

    Answer

    no

    nil is falsy, so the else branch runs.

  7. What does this program print? IO.inspect(if false, do: 42)

    Answer

    nil

    An if without else returns nil when its condition is false.

  8. What does this program print? IO.puts(if !true, do: "hidden", else: "shown")

    Answer

    shown

    The bang flips true to false, so the do branch is skipped and the else branch runs.

  9. What does this program print? x = 5 IO.puts(if x > 3, do: "big", else: "small")

    Answer

    big

    The comparison is true, so the do branch is printed.

  10. What does this program do? value = if false, do: 42 IO.puts(value + 1)

    Answer

    An ArithmeticError, because value is nil

    The if produced nil, and nil is not a number for the + operator.

Автор статьи: Arthur Isaev