Created
August 1, 2016 14:44
-
-
Save rawman/7093272c8c09ec13c436a6314ff27085 to your computer and use it in GitHub Desktop.
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
def map(collection, fun \\ &(&1)) do | |
map_impl(collection, &spawn/1, &(invoke(fun, &1))) | |
end | |
def map!(collection, fun \\ &(&1)) do | |
map_impl(collection, &spawn_link/1, fun) | |
end | |
defp map_impl(collection, spawn_fun, fun) do | |
me = self | |
collection | |
|> Enum.map(fn (elem) -> | |
spawn_fun.(fn -> (send me, { self, fun.(elem) }) end) | |
end) | |
|> Enum.map(fn (pid) -> | |
receive do { ^pid, result } -> result end | |
end) | |
end | |
defp invoke(fun, elem) do | |
try do | |
{:ok, fun.(elem)} | |
rescue | |
e -> {:error, e} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment