Every developer “worth their salt” knows how to implement FizzBuzz, It is a program which prints the following:
1 | defmodule FizzBuzz do |
Let us see a few possible ways to do this in Elixir!
1. Use if
1 | def fb_if(n) do |
That is some real ugly code, it is exacerbated by the fact that Elixir doesn’t allow early returns.
2. Use cond
1 | def fb_cond1(n) do |
This is a huge improvement, I really think this captures the problem the solution in a very readable way.
3. Use cond with better predicates
1 | def divisible_by_3?(n), do: rem(n, 3) == 0 |
Using separate predicates improves the readability further.
4. Use case
1 | def fb_case(n) do |
This is a concise chunk of code but isn’t as readable as the one that uses cond.
5. Use pattern matching in functions
1 | def fb_fun1(n) do |
I think this is actually less readable than the one that uses case as the logic.
6. Use guard clauses in functions
1 | def fb_fun2(n) when rem(n, 3) == 0 and rem(n, 5) == 0, do: "FizzBuzz" |
This feels like an improvement to the previous implementation readability wise.
7. Use custom made guard clauses in functions
1 | defguard is_divisible_by_3(n) when rem(n, 3) == 0 |
I like this one a lot, it feels very terse and reads like a mathematical equation.
Which version do you personally find more readable? I feel like the last one and the implementation using cond are the more readable versions.
Here is the piece of code containing all implementations:
1 | defmodule Fizzbuzz do |