Skip to content

Instantly share code, notes, and snippets.

@tastywheat
Created January 20, 2016 13:03
Show Gist options
  • Save tastywheat/244baa40e0113e8eb4af to your computer and use it in GitHub Desktop.
Save tastywheat/244baa40e0113e8eb4af to your computer and use it in GitHub Desktop.
elixir parallel map
defmodule Foo do
def map([], _func) do
[]
end
def map([head|tail], func) do
[func.(head) | map(tail, func)]
end
def child(item, func, parent) do
send(parent, {self(), func.(item) })
end
def spawn_children(collection, func) do
map(collection, fn item -> spawn(__MODULE__, :child, [item, func, self()]) end)
end
def collect_results(pids) do
map(pids, fn pid -> receive do
{^pid, value} -> value
end
end)
end
def pmap(collection, func) do
collection
|> spawn_children(func)
|> collect_results
end
end
IO.inspect Foo.pmap([1,2,3,4], fn x -> x+1 end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment