Last active
August 29, 2015 14:10
-
-
Save citizen428/8a2f80b3a5bd58f39ed4 to your computer and use it in GitHub Desktop.
Elixir FizzBuzz server
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 FizzBuzz do | |
def compute do | |
receive do | |
n -> IO.puts compute(n) | |
end | |
compute | |
end | |
defp compute(n) do | |
case {rem(n, 3), rem(n, 5)} do | |
{0, 0} -> :FizzBuzz | |
{0, _} -> :Fizz | |
{_, 0} -> :Buzz | |
_ -> n | |
end | |
end | |
end | |
# Usage example: | |
# fb = spawn FizzBuzz, :compute, [] | |
# for x <- 1..15, do: send(fb, x) | |
# Enum.map(1..15, &send(fb, &1)) |
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 FizzBuzz do | |
use GenServer | |
## Client API | |
def start(opts \\ []), do: GenServer.start_link(__MODULE__, :ok, opts) | |
def compute(server, n), do: GenServer.call(server, {:print, n}) | |
## Server Callbacks | |
def init(:ok) do | |
IO.puts "FizzBuzz server started" | |
{:ok, %{}} | |
end | |
def handle_call({:print, n}, _from, state) do | |
if Dict.has_key?(state, n) do | |
IO.puts "Fetching #{n}" | |
{:ok, s} = Dict.fetch(state, n) | |
else | |
IO.puts "Calculating #{n}" | |
s = case {rem(n, 3), rem(n, 5)} do | |
{0, 0} -> :FizzBuzz | |
{0, _} -> :Fizz | |
{_, 0} -> :Buzz | |
_ -> n | |
end | |
end | |
IO.puts s | |
{:reply, s, Dict.put(state, n, s)} | |
end | |
end | |
# Usage example | |
# {:ok, fb} = FizzBuzz.start | |
# 1..15 |> Enum.map(&FizzBuzz.compute(fb, &1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment