cond

The cond macro lets you list out a series of conditions, each with associated code. It executes the code corresponding to the first truthy conditions.

In the game of FizzBuzz, children count up from 1. If the number is a multiple of three, they say “Fizz.” For multiples of five, they say “Buzz.” For multiples of both, they say “FizzBuzz.” Otherwise, they say the number.

In Elixir, we could code this as follows:

1: defmodule​ FizzBuzz ​do
def​ upto(n) ​when​ n > 0, ​do​: _upto(1, n, [])
5: defp​ _upto(_current, 0, result), ​do​: Enum.reverse result
defp​ _upto(current, left, result) ​do
next_answer =
cond​ ​do
10:  rem(current, 3) == 0 ​and​ rem(current, 5) == 0 ->
"​​FizzBuzz"

Get Programming Elixir 1.3 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.