Parallel Map—The “Hello, World” of Erlang

Devin Torres reminded me that every book in the Erlang space must, by law, include a definition of a parallel map function. Regular map returns the list that results from applying a function to each element of a collection. The parallel version does the same, but it applies the function to each element in a separate process.

spawn/pmap.exs
 
defmodule​ Parallel ​do
 
def​ pmap(collection, fun) ​do
 
me = self
 
collection
 
|> Enum.map(​fn​ (elem) ->
 
spawn_link ​fn​ -> (send me, { self, fun.(elem) }) ​end
 
end​)
 
|> Enum.map(​fn​ (pid) ->
 
receive​ ​do​ { ^pid, result } -> result ​end
 
end​)
 
end
 
end

Our method contains two transformations (look for the |> operator). The first transformation ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.