O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required