Created
June 18, 2015 20:55
-
-
Save jwhiteman/83a550655ed3e6817563 to your computer and use it in GitHub Desktop.
elixir ring
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 Ring do | |
def node(name, next_pid) do | |
receive do | |
1 -> | |
send next_pid, 1 | |
n when is_number(n) -> | |
send next_pid, n | |
node(name, next_pid) | |
end | |
end | |
def create_processes(n, m) when n > 1 do | |
last = Enum.reduce 1..n-1, self, | |
fn (name, send_to) -> | |
spawn(Ring, :node, [name, send_to]) | |
end | |
send last, m | |
base(last) | |
end | |
def base(next_pid) do | |
receive do | |
1 -> IO.puts "Done." | |
n when is_number(n) -> | |
send next_pid, n - 1 | |
base(next_pid) | |
end | |
end | |
def run(n, m) do | |
IO.puts inspect :timer.tc(Ring, :create_processes, [n, m]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment