我还是新编程和全新的erlang(2周新手!)。我编辑了一点,所以至少它会编译运行。但我仍然无法弄清楚将结果发送到“加入者过程”以加入所有单独结果的概念。
它会拆分并发送收到的“块”以计算块数。只是不知道如何让所有这些流程加入他们的个人结果。我有点理解下面这个概念,但不知道它是如何得到启发的。我已经尝试了很多天和几个小时来达到这一点,但是如果没有错误或未绑定的变量等,它就无法做任何事情。
-module (ccharcount1d).
-compile(export_all).
load(F)->
{ok, Bin} = file:read_file(F),
List=binary_to_list(Bin),
Ls=string:to_lower(List),
Length=round(length(List)/20),
Collect_Results = spawn(ccharcount1d, collect_results, []),
Sl=split(Ls,Length),
io:fwrite("Loaded, Split, and sent to multiple processes~n").
%%splits txt file into "chunks" and sends those "chunks" to be processed
split([],_)->[];
split(List,Length)->
S1=string:substr(List,1,Length),
case length(List) > Length of
true->S2=string:substr(List,Length+1,length(List)),
Process_Split = spawn(ccharcount1d,receive_splits,[]),
Process_Split ! {self(), S1};
false->S2=[],
Process_Split = spawn(ccharcount1d,receive_splits,[]),
Process_Split ! {self(), S1}
end,
[S1]++split(S2,Length).
%%recieves the split "chunks" and counts the results
receive_splits()->
receive
{From, S1} ->
Result=go(S1)
%Collect_Results ! Result
end.
collect_results()->
receive
{Process_Split, Result} ->
Result=join([],Result)
end.
join([],[])->[];
join([],R)->R;
join([H1 |T1],[H2|T2])->
{C,N}=H1,
{C1,N1}=H2,
[{C1,N+N1}]++join(T1,T2).
count(Ch, [],N)->N;
count(Ch, [H|T],N) ->
case Ch==H of
true-> count(Ch,T,N+1);
false -> count(Ch,T,N)
end.
go(L)->
Alph=[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z],
rgo(Alph,L,[]).
rgo([H|T],L,Result)->
N=count(H,L,0),
Result2=Result++[{[H],N}],
rgo(T,L,Result2);
rgo([],L,Result)-> Result.
答案 0 :(得分:3)
再次,我是新人。我理解这个概念。我不理解 语法。如何“将Pid传递给工人流程”
start() ->
Work = ...,
JoinPid = spawn(fun() -> join_func([]) end),
WorkerPid = spawn(fun() -> worker_func(JoinPid, Work) end), %Pass JoinPid to worker process.
...
join_func(Acc) ->
receive
Result ->
join_func([Result|Acc]); %Recursive function call--the life blood of all functional languages.
...
end
worker_func(JoinPid, Work) ->
Result = ... Work ...,
JoinPid ! Result. %Worker process uses JoinPid to send back the results.
另外,请查看:
8> [$a, $b, $c].
"abc"
9> "abc".
"abc"
输出显示[$a, $b, $c]
相当于"abc"
。这意味着你可以这样写:
[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z]
更加简洁如此:
"abcdefghijklmnopqrstuvwxyz"
甚至更多,像这样:
11> lists:seq(97, 122).
"abcdefghijklmnopqrstuvwxyz"
答案 1 :(得分:2)
您需要同步go函数的输出。 不要在里面生成函数因为我看到所有结果都会进入不同的进程(receive_results)。
最佳解决方案只产生一个进程,用于仅在加载函数内连接结果(此过程将self()作为输入,以便它可以将最终结果发送回加载函数)。然后将该连接过程引用(J_PID)传递给所有工作者将结果发送回加入进程的进程。加入进程是一种receive_results循环。当所有组块被处理时,循环终止。添加一个子句来终止加入进程。终止时,加入进程将结果发送回加载函数。
Sudo代码:
J_PID = spawn join(self())
溢出(J_PID,....)
wait_for_result(收到结果 - > R)