Created
March 3, 2014 14:57
-
-
Save benjamintanweihao/9326709 to your computer and use it in GitHub Desktop.
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 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