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