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), ... |
Get Functional Programming: A PragPub Anthology 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.