Skip to content

Instantly share code, notes, and snippets.

@esehara
Created July 21, 2016 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esehara/d51b0f505d5e87d5988b96b6dd35c40d to your computer and use it in GitHub Desktop.
Save esehara/d51b0f505d5e87d5988b96b6dd35c40d to your computer and use it in GitHub Desktop.
ElixirのマクロでFizzBuzz
defmodule FizzBuzzDefine do
def define_taple do
[{"fizz", 3}, {"Buzz", 5}]
end
end
defmodule FizzBuzzHelper do
import FizzBuzzDefine
defmacro mod_zero_string do
for {name, x} <- define_taple do
quote do
def unquote(:"#{name}")(x) do
if rem(x, unquote(x)) == 0 do
unquote(name)
else
""
end
end
end
end
end
defmacro define_to_s do
functions = Enum.map(define_taple, &(elem(&1, 0)))
quote do
def to_s(i) do
function_strings = Enum.map_join(unquote(functions), &(apply(FizzBuzz, :"#{&1}", [i])))
if function_strings == "", do: to_string(i), else: function_strings
end
end
end
end
defmodule FizzBuzz do
import FizzBuzzHelper
mod_zero_string
define_to_s
def forprint(x) do
for i <- 1..x do
IO.puts to_s(i)
end
end
end
FizzBuzz.forprint(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment