O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

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

A Final Example

Let’s use our knowledge of actors to write one final example program. This is a library that implements the map function. (The map function takes a collection and applies a function to each element, returning a new collection containing the results of each function call.) However, we’ll make this example more interesting by running each computation in a separate process. Without further ado, here’s the code:

 defmodule​ Parallel ​do
 
 import​ Enum, ​only:​ [​map:​ 2]
 
 # Parallel map
 def​ pmap(collection, fun) ​do
  collection |> spawn_children(fun) |> collect_results
 end
 
 defp​ spawn_children(collection, fun), ​do​: collection |> map(&spawn_child(&1, fun))
 
 def​ spawn_child(item, fun), ...

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