Skip to content

Instantly share code, notes, and snippets.

@benjamintanweihao
Created June 19, 2013 17:26
Show Gist options
  • Save benjamintanweihao/5816137 to your computer and use it in GitHub Desktop.
Save benjamintanweihao/5816137 to your computer and use it in GitHub Desktop.
My own notes in explains the chain.exs in Programming Elixir, Chapter 12
defmodule Chain do
# There are a couple of interesting things to note in this example.
# Take a look at the 'counter' function:
# It takes in a pid, NOT 'n'.
# 'n' will be received in the form of a message (i.e. pid <- msg )
# In a sense, we are 'loading/setting up' the function first.
def counter(next_pid) do
receive do
n ->
next_pid <- n + 1
end
end
def create_processes(n) do
# I thought of this like a domino. Enum.reduce 'prepares' all the processes
# by passing in the arguments to the functions.
last = Enum.reduce 1..n, self,
fn(_,send_to) -> spawn(Chain, :counter, [send_to]) end
# This is when the first 'domino' starts to topple the rest (i.e. kickstarts the chain reaction)
last <- 0
# So how did we come to here?
# Recall what is passed as the first argument? 'self'!
# So, 'self' will be the very last to be sent the message.
# By then, we would have our answer ready.
receive do
final_answer ->
"Result is #{final_answer}"
end
end
def run(n) do
IO.puts inspect :timer.tc(Chain, :create_processes, [n])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment