Created
January 20, 2016 13:03
-
-
Save tastywheat/244baa40e0113e8eb4af to your computer and use it in GitHub Desktop.
elixir parallel map
This file contains hidden or 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 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