Skip to content

Instantly share code, notes, and snippets.

@benjamintanweihao
Created March 3, 2014 14:57
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 benjamintanweihao/9326709 to your computer and use it in GitHub Desktop.
Save benjamintanweihao/9326709 to your computer and use it in GitHub Desktop.
defmodule Acky do
defmodule Client do
def start do
spawn(__MODULE__, :loop, [])
end
def loop do
receive do
{from, {:ok, result}} ->
IO.puts "Got result: #{result}"
from |> send :ok
loop
_ ->
IO.puts "Unexpected message!"
loop
end
end
end
defmodule Server do
def start do
spawn(__MODULE__, :loop, [ HashDict.new ])
end
def loop(cache) do
receive do
{:compute, {reply_to, {m, n}}} ->
case HashDict.fetch(cache, {m, n}) do
{:ok, result} ->
IO.puts "[CACHE HIT]: #{result}"
reply_to |> send({self, {:ok, result}})
receive do
_ -> :ok
end
:error ->
result = ackermann(m, n)
IO.puts "[CACHE MISS]: #{result}"
cache = cache |> HashDict.put({m,n}, result)
reply_to |> send({self, {:ok, result}})
end
loop(cache)
:view_cache ->
IO.inspect cache
loop(cache)
:stop -> :ok
_ ->
IO.puts "Unexpected message!"
loop(cache)
end
end
defp ackermann(0, n), do: n + 1
defp ackermann(m, 0), do: ackermann(m-1, 1)
defp ackermann(m, n), do: ackermann(m-1, ackermann(m,n-1))
end
end
client = Acky.Client.start
server = Acky.Server.start
server |> send {:compute, {client, {3,2}}}
server |> send {:compute, {client, {4,1}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment