Skip to content

Instantly share code, notes, and snippets.

@adamu
Forked from jarednorman/fizzbuzz.markdown
Last active April 28, 2022 11:16
Show Gist options
  • Select an option

  • Save adamu/324b54b48dff1af2cdac0853274178bc to your computer and use it in GitHub Desktop.

Select an option

Save adamu/324b54b48dff1af2cdac0853274178bc 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 fizzbuzz(n) do
    1 .. n
    |> Stream.map(&calc/1)
    |> Enum.each(&IO.puts/1)
  end

  defp calc(i) when rem(i, 15) == 0, do: "FizzBuzz"
  defp calc(i) when rem(i, 3)  == 0, do: "Fizz"
  defp calc(i) when rem(i, 5)  == 0, do: "Buzz"
  defp calc(i),                      do: i
end

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

@adamu
Copy link
Author

adamu commented Jun 30, 2021

Version that doesn't repeat the 3 and 5 calculations for 15:

defmodule Example do
  def fizzbuzz do
    Enum.each(1..100, fn i -> {"", i} |> fizz() |> buzz() |> print() end)
  end

  def fizz({_, num}) when rem(num, 3) == 0, do: {"Fizz", num}
  def fizz(fizz), do: fizz

  def buzz({fizz, num}) when rem(num, 5) == 0, do: {fizz <> "Buzz", num}
  def buzz(buzz), do: buzz

  def print({"", num}), do: IO.puts(num)
  def print({fizzbuzz, _}), do: IO.puts(fizzbuzz)
end

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