Last active
May 11, 2018 08:43
-
-
Save andrewshatnyy/01bdde65dceb2c9fc4311215c31848c4 to your computer and use it in GitHub Desktop.
Pmap in Elixir the old way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Pmap do | |
@moduledoc """ | |
Parrallel map calculator | |
Calculates a result of a &function/1 | |
""" | |
@doc """ | |
emit a process, which calculates a number | |
and sends a message | |
""" | |
def emit(arg, main_ref) do | |
spawn fn -> | |
send(main_ref, {self(), function(arg)}) | |
end | |
end | |
def emit(arg, main_ref, func) do | |
spawn fn -> | |
send(main_ref, {self(), func.(arg)}) | |
end | |
end | |
@doc """ | |
listens on a process, blocks, | |
matches exactly on the pid in order to preserve the place in the list | |
""" | |
def listen(pid) do | |
receive do | |
{^pid, result} -> result | |
end | |
end | |
@doc """ | |
Calculator | |
## Examples | |
iex> [1,2,3] |> Pmap.calc() | |
[1,4,9] | |
iex> [1,2,3] |> Pmap.calc(fn(n)-> :math.pow(n,n) |> Kernel.trunc() end) | |
[1, 4, 27] | |
""" | |
def calc(arr) do | |
arr | |
|> Enum.map(&emit(&1, self())) | |
|> Enum.map(&listen/1) | |
end | |
def calc(arr, fun) do | |
arr | |
|> Enum.map(&emit(&1, self(), fun)) | |
|> Enum.map(&listen/1) | |
end | |
def function(n), do: n * n | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment