Skip to content

Instantly share code, notes, and snippets.

@thiagoa
Last active February 25, 2016 01:15
Show Gist options
  • Save thiagoa/48b0843a9d75a4d83c40 to your computer and use it in GitHub Desktop.
Save thiagoa/48b0843a9d75a4d83c40 to your computer and use it in GitHub Desktop.
defmodule FizzBuzz do
defmacro __using__(_) do
quote do
alias FizzBuzz.FunctionSignaturePatternMatching, as: FSPM
alias FizzBuzz.GuardClause
alias FizzBuzz.Case
alias FizzBuzz.Cond
alias FizzBuzz.If
import FizzBuzz.AnonymousFunction
end
end
defmodule FunctionSignaturePatternMatching do
def run(n) do
match rem(n, 3), rem(n, 5), n
end
defp match(0, 0, _) do
"FizzBuzz"
end
defp match(0, _, _) do
"Fizz"
end
defp match(_, 0, _) do
"Buzz"
end
defp match(_, _, n) do
n
end
end
defmodule GuardClause do
def run(n) when rem(n, 3) == 0 and rem(n, 5) == 0 do
"FizzBuzz"
end
def run(n) when rem(n, 3) == 0 do
"Fizz"
end
def run(n) when rem(n, 5) == 0 do
"Buzz"
end
def run(n) do
n
end
end
defmodule Case do
def run(n) do
case {rem(n, 3), rem(n, 5), n} do
{0, 0, _} -> "FizzBuzz"
{0, _, _} -> "Fizz"
{_, 0, _} -> "Buzz"
{_, _, n} -> n
end
end
end
defmodule Cond do
def run(n) do
cond do
rem(n, 3) == 0 and rem(n, 5) == 0 -> "FizzBuzz"
rem(n, 3) == 0 -> "Fizz"
rem(n, 5) == 0 -> "Buzz"
true -> n
end
end
end
defmodule If do
def run(n) do
if rem(n, 3) == 0 and rem(n, 5) == 0 do
"FizzBuzz"
else
if rem(n, 3) == 0 do
"Fizz"
else
if rem(n, 5) == 0 do
"Buzz"
else
n
end
end
end
end
end
defmodule AnonymousFunction do
def anonymous_function do
fn n ->
matcher = fn
0, 0, _ -> "FizzBuzz"
0, _, _ -> "Fizz"
_, 0, _ -> "Buzz"
_, _, n -> n
end
matcher.(rem(n, 3), rem(n, 5), n)
end
end
end
end
defmodule BareBonesIterator do
def run(range, function) when is_map(range) do
run Enum.to_list(range), function
end
def run([n|tail], function) do
IO.puts function.(n)
run(tail, function)
end
def run([], _function), do: nil
end
defmodule Runner do
use FizzBuzz
Enum.each 10..16, fn n ->
IO.puts FSPM.run(n)
end
IO.puts ""
10..16 |> Enum.map fn n ->
IO.puts GuardClause.run(n)
end
IO.puts ""
10..16 |> Enum.map fn n ->
IO.puts anonymous_function.(n)
end
IO.puts ""
BareBonesIterator.run 10..16, &Case.run/1
IO.puts ""
10..16 |> Enum.map(&Cond.run/1) |> Enum.each(&IO.puts/1)
IO.puts ""
10..16 |> Enum.map fn n ->
IO.puts If.run(n)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment