Skip to content

Instantly share code, notes, and snippets.

@josephwilk
Created July 30, 2013 20:06

Revisions

  1. josephwilk created this gist Jul 30, 2013.
    38 changes: 38 additions & 0 deletions future.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    defmodule Future do
    def new(fun) do
    fn(x) ->
    spawn_link fn ->
    value = try do
    { :ok, fun.(x) }
    rescue
    e -> { :error, e }
    end

    receive do
    pid ->
    pid <- {self, value}
    end
    end
    end
    end

    def value(pid, timeout // :infinity, default // {:error, :timeout}) do
    pid <- self
    receive do
    {^pid, {:ok, value}} -> value
    {^pid, {:error, e}} -> raise e
    after
    timeout -> default
    end
    end
    end

    defmodule Parallel do
    def pmap(collection, fun) do
    collection
    |> Enum.map(Future.new(fun))
    |> Enum.map(Future.value(&1, 1000, {:error}))
    end
    end

    IO.inspect Parallel.pmap([1,2,3,4], fn x -> :timer.sleep(1000); x+1 end)