O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

control/fizzbuzz.ex
Line 1 
defmodule​ FizzBuzz ​do
def​ upto(n) ​when​ n > 0, ​do​: _upto(1, n, [])
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"
-  ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required