[erlang-questions] On Loop

黃耀賢 (Yau-Hsien Huang) g9414002.pccu.edu.tw@REDACTED
Sun Jul 17 19:51:34 CEST 2011


Hi, everyone. I did exercises on basic problems, with the following
loop structure:

for(I, Fp, Fi, Fc) ->
    case Fp(I) of
        true ->
            Fc(I),
            I1 = Fi(I),
            for(I1, Fp, Fi, Fc);
        false ->
            ok
    end.

where I is loop index, Fp, Fi, and Fc are functions for loop predicate,
incremental state, and loop context. Then I can write some normal
for-loop instructions, such as 9x9 multiple table. (In my country,
when we're children, we read and remember the 9x9 multiple table,
so it's a famous material for us.) To write a program like
"for(i=0; i<10; i++) { ... }" in C++, functions are defined as these:

    fp(I) -> I < 10.
    fi(I) -> I+1.

It's
    for (i=2; i<10; i++)
        for (j=1; j<10; j++)
            cout << i << " * " << j << " = " << (i*j) << endl;
so fc/1 shell be a loop.

    fc(I) ->
        for(I, fun fp/1, fun fi/1, fc1(I)).

    fc1(I) ->
        fun(J) ->
            io:format("~w x ~w = ~w~n", [I, J, I*J]).
        end.

    multiple() ->
        for(2, fun fp/1, fun fi/1, fun fc/1).

Then, I got it work.

Now I get an image that an index variable in imperative languages
means a sequence of values or states, and then in functional
languages it's corresponding to a list of values. So when I want
9x9 table, in C++ I need a variable but in Erlang I need a list with
length 81.

And, in my imagination, all data in Erlang is put in stack. So, when
I use 81 cells, they occupy memory with 81 units, right?

And, in my imagination, memory is free if a function execution ends,
so by using loops above I partially save memory because of using
nested for/4, right?

-- 

Best Regards.

--- Y-H. H.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110718/cfd08ac6/attachment.htm>


More information about the erlang-questions mailing list