Erlang无原生for循环,但代码使用for()函数,求解析
for/3 Function in Your Erlang Code Hey there! Let's clear up this confusion right away: Erlang doesn't have a built-in for loop, so that for() function in your code is a custom recursive helper (written by someone, not part of core Erlang). Let's break this down completely.
First, let's fill in the missing parts of your code snippet—this is the full, common version of what you're working with:
-module(helloworld). -export([max/1, start/0, for/3, wait/0]). max(N) -> Max = erlang:system_info(process_limit), io:format("Maximum allowed processes:~p~n", [Max]), statistics(runtime), statistics(wall_clock), % This is the for function you're confused about L = for(1, N, fun() -> spawn(fun() -> wait() end) end), {_, Time1} = statistics(runtime), {_, Time2} = statistics(wall_clock), lists:foreach(fun(Pid) -> exit(Pid, kill) end, L), io:format("Runtime: ~p ms, Wall clock: ~p ms~n", [Time1, Time2]). start() -> max(100000). % The custom for/3 recursive function for(Max, Max, F) -> [F()]; for(I, Max, F) -> [F() | for(I+1, Max, F)]. wait() -> receive _ -> ok end.
What the for/3 Function Does
Since Erlang is a functional language, it uses recursion instead of imperative loops (like for in C/Java). This for/3 function mimics a loop by recursively building a list of results:
Termination Clause:
for(Max, Max, F) -> [F()];
When the starting indexIequals the end indexMax, we run the functionFonce, wrap its result in a list, and stop the recursion. This is the "end of the loop" condition.Recursive Clause:
for(I, Max, F) -> [F() | for(I+1, Max, F)]
For every indexIthat's less thanMax, we first runF()(in your code, this spawns a new process), then recursively callforwithI+1(incrementing the "loop counter"). The|operator appends the currentF()result to the list generated by the recursive call.
How It's Used in Your Code
In the line L = for(1, N, fun() -> spawn(fun() -> wait() end) end):
- We're "looping" from 1 to
N - On each iteration, we spawn a new Erlang process that runs the
wait()function (which sits idle waiting for a message) - The final result
Lis a list of all the PIDs (process IDs) of the spawned processes
This code is a common benchmark to test how quickly Erlang can spawn large numbers of processes, which is one of its key strengths.
内容的提问来源于stack exchange,提问作者Alex. Smith

