Skip to content

Instantly share code, notes, and snippets.

@jarednorman
Created February 22, 2016 07:59
Show Gist options
  • Save jarednorman/a2abe713fd66e334f480 to your computer and use it in GitHub Desktop.
Save jarednorman/a2abe713fd66e334f480 to your computer and use it in GitHub Desktop.
Fizzbuzz in Elixir

Fizzbuzz in Elixir

Elixir is a beautiful language. Among its strength is its powerful pattern matching system which allows one to write very declarative, elegant code. FizzBuzz is a trivial problem often presented to new programmers or interviewees to determine baseline programming ability. Here is a solution Elixir:

defmodule FizzBuzz do
  def fizz do
    (1..100)
    |> Enum.map(&buzz/1)
    |> Enum.each(&IO.puts/1)
  end

  defp buzz(i) when rem(i, 15) == 0, do: "FizzBuzz"
  defp buzz(i) when rem(i, 5)  == 0, do: "Buzz"
  defp buzz(i) when rem(i, 3)  == 0, do: "Fizz"
  defp buzz(i),                      do: Integer.to_string(i)
end

This kind of declarative syntax frequently makes handling changes in business requirements as easy as adding an additional definition for a function.

@jarednorman
Copy link
Author

No reason to use map if you're just going to call IO.puts in there.

@vKxni
Copy link

vKxni commented Nov 29, 2022

defmodule FizzBuzz do
  def build_list(range, types),
    do: Enum.map(range, &entry(&1, types))

  defp entry(n, types) do
    for {d, val} <- types,
        rem(n, d) == 0,
        reduce: n do
      acc when is_integer(acc) -> val
      acc -> [acc, val]
    end
    |> to_string()
  end
end

types = [
  {3, "Fizz"},
  {5, "Buzz"}
]

1..100
|> FizzBuzz.build_list(types)
|> Enum.intersperse(?\n)
|> IO.puts()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment