Created
July 21, 2016 18:22
-
-
Save esehara/d51b0f505d5e87d5988b96b6dd35c40d to your computer and use it in GitHub Desktop.
ElixirのマクロでFizzBuzz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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