Skip to content

Instantly share code, notes, and snippets.

@citizen428

citizen428/fizzbuzz.ex

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.