Skip to content

Instantly share code, notes, and snippets.

@rawman
Created August 1, 2016 14:44
Show Gist options
  • Save rawman/7093272c8c09ec13c436a6314ff27085 to your computer and use it in GitHub Desktop.
Save rawman/7093272c8c09ec13c436a6314ff27085 to your computer and use it in GitHub Desktop.
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