Skip to content

Instantly share code, notes, and snippets.

@fschuindt
Created October 28, 2016 21:54
Show Gist options
  • Save fschuindt/ddf64ed4a13c908336aac205710a7a03 to your computer and use it in GitHub Desktop.
Save fschuindt/ddf64ed4a13c908336aac205710a7a03 to your computer and use it in GitHub Desktop.
# Challenge 1: Given a list of integers, create a module that maps that list
# into different processes. Deliver to those processes the element and a
# function to be performed with it. This function can be anything, for
# instance: "Returns square of the number". Finally each process shoud send
# a message to the spawning process with the result.
defmodule Spawner do
@moduledoc """
Maps a list into processes performing a given function. Each one sends a
message to the spawning process, this one uses the IO module to print it out.
## Examples
iex> Spawner.map([1, 2, 3], fn(x) -> x * 2 end)
2
4
6
"""
@spawner self
def map(list, func) do
list
|> Enum.map(fn element -> spawn(fn ->
send(@spawner, {self, func.(element)})
end) end)
|> Enum.map(fn pid ->
receive do
{^pid, result} -> IO.puts result
end
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment