DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
 
rawkode profile image
David McKay

There's a lack of pattern matching and recursion in the comments, so here we go:

defmodule FizzBuzz do
  def run(0) do
    IO.puts("Finished")
  end

  def run(n) when is_integer(n) do
    n
    |> fizzbuzz(rem(n, 3), rem(n, 5))
    |> run()
  end

  defp fizzbuzz(n, 0, 0) do
    IO.puts("#{n}: FizzBuzz")

    n - 1
  end

  defp fizzbuzz(n, 0, _) do
    IO.puts("#{n}: Fizz")
    n - 1
  end

  defp fizzbuzz(n, _, 0) do
    IO.puts("#{n}: Buzz")
    n - 1
  end

  defp fizzbuzz(n, _, _) do
    IO.puts("#{n}")
    n - 1
  end
end

Collapse
 
nombrekeff profile image
Keff

Nice, thanks for sharing this approach.

Rickard Laurin just posted another similar approach in ReasonML as well.