Iterate n times

Raimo Niskanen raimo@REDACTED
Mon Feb 4 10:04:27 CET 2002

You can make up numerous variants of this idea. Here is another one:

%% A simple loop construct.
%% Calls 'Fun' with argument 'Start' first and then repeatedly with
%% its returned value (state) until 'Fun' returns 'Stop'. Then
%% the last state value that was not 'Stop' is returned.

iterate(Start, Done, Fun) when function(Fun) ->
    iterate(Start, Done, Fun, Start).

iterate(Done, Done, Fun, I) ->
iterate(I, Done, Fun, _) ->
    iterate(Fun(I), Done, Fun, I).

1>iterate([1], done, fun ([5|_])->done; (L)->[hd(L)+1|L] end).

Another thought is to make lists:seq/3 accept a fun as incrementor.

The problem might be that everytime a user comes up with this kind of
construct, it looks slightly different, so there is no obvious
one-size-fits-all solution. Furthermore, if you give the user another
loop construct it is just another way for the user to shoot her/himself
in the foot.

/ Raimo Niskanen, Ericsson UAB, Erlang/OTP

Sean Hinde wrote:
> Does anyone know if this function has a proper name or already exists
> anywhere?
> iter(F, St, 0) ->
>     St;
> iter(F, St, N) when integer(N), N > 1 ->
>     iter(F, F(St, N), N-1).
> Simple examples of usage might be:
> 1> iter(fun(St, N) -> N + St end, 0, 5).
> 15
> 2> iter(fun(St, N) -> [N|St] end, [], 5).
> [1,2,3,4,5]
> Sean
> This email (including attachments) is confidential.  If you have received
> this email in error please notify the sender immediately and delete this
> email from your system without copying or disseminating it or placing any
> reliance upon its contents.  We cannot accept liability for any breaches of
> confidence arising through use of email.  Any opinions expressed in this
> email (including attachments) are those of the author and do not necessarily
> reflect our opinions.  We will not accept responsibility for any commitments
> made by our employees outside the scope of our business.  We do not warrant
> the accuracy or completeness of such information.

More information about the erlang-questions mailing list