You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Erlang无原生for循环,但代码使用for()函数,求解析

Understanding the Custom 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 index I equals the end index Max, we run the function F once, 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 index I that's less than Max, we first run F() (in your code, this spawns a new process), then recursively call for with I+1 (incrementing the "loop counter"). The | operator appends the current F() 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 L is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:32:42