Every developer “worth their salt” knows how to implement FizzBuzz, It is a program which prints the following:
defmodule FizzBuzz do
Let us see a few possible ways to do this in Elixir!
def fb_if(n) do
That is some real ugly code, it is exacerbated by the fact that Elixir doesn’t allow early returns.
def fb_cond1(n) do
This is a huge improvement, I really think this captures the problem the solution in a very readable way.
def divisible_by_3?(n), do: rem(n, 3) == 0
Using separate predicates improves the readability further.
def fb_case(n) do
This is a concise chunk of code but isn’t as readable as the one that uses cond.
def fb_fun1(n) do
I think this is actually less readable than the one that uses case as the logic.
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.
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:
defmodule Fizzbuzz do