Use of the cond Keyword
Explore how to implement control flow in Elixir using the cond keyword. Understand its structure by coding examples such as FizzBuzz, review alternatives, and learn when to use cond versus pattern matching for clean, idiomatic Elixir code.
The cond macro lets us list out a series of conditions, each with an associated code. It executes the code corresponding to the first true condition.
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.
Case 1
In Elixir, we could code this as shown in the terminal below.
Run c("fizzbuzz.ex") and FizzBuzz.upto(20) commands to ...