Erlang的作者Joe Armstrong发表了一段代码来表示MapReduce版本的Erlang标准lists:map/2方法
Map阶段:在这个阶段,通过Map过程,将原始数据列表,处理成中间数据,用于Reduce过程的处理
Reduce阶段:将Map阶段产生的中间数据综合归纳成输出结果
先看看下面这段代码,实现了lists:map/2的分布式计算
-module(pmap).
-export([pmap/2]).
pmap(F, L) ->
S = self(),
Pids = lists:map(fun(I) ->
spawn(fun() -> do_fun(S, F, I) end)
end, L),
gather(Pids).
%% Reduce
gather([]) -> [];
gather([H|L]) ->
receive
{
H, Result} -> [Result|gather(L)]
end.
%% Map = F,F(I)生成MapResult中间结果
do_fun(Parent, F, I) ->
Parent ! {
self(), (catch F(I))}.
扩展一下应用到我们快排中,代码如下:
-module(map_reduce).
-export([map_reduce/