May 2018
Intermediate to advanced
412 pages
9h 3m
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:
| 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" |
| - | rem(current, ... |
Read now
Unlock full access