Skip to content

Instantly share code, notes, and snippets.

@citizen428
Last active August 29, 2015 14:10
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 citizen428/8a2f80b3a5bd58f39ed4 to your computer and use it in GitHub Desktop.
Save citizen428/8a2f80b3a5bd58f39ed4 to your computer and use it in GitHub Desktop.
Elixir FizzBuzz server
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))
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