[erlang-questions] On Loop

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Sun Jul 17 20:28:59 CEST 2011


2011/7/17 黃耀賢 (Yau-Hsien Huang) <g9414002.pccu.edu.tw@REDACTED>:

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

I am not entirely sure what you are asking, but note that in your
function, the recursive call to for/4 is in tail-position. This means
that the tail-call-optimization is applicable.

> 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?

Not if the tail-call-optimization trigger! Then it is 1 unit, and the
function uses as much memory as the C++ module a constant factor. And
I dare say it does in your case.

A more erlang-idiomatic way of encoding your problem is the following:

[io:format("~B x ~B = ~B~n", [I, J, I*J])
    || I <- lists:seq(2,10), J <- lists:seq(2,10)].

Here is the basic idea:

1. Create the list [2,3,...,9] = lists:seq(2,9) two times.
2. Use a List Comprehension. Iterate through the elements [2,3,...,9]
and call it I. The semantics of list comprehensions are that for each
of these, the list comprehension will carry out its second part which
is to iterate J through [2,3,...,9]. In other words, we create the
cartesian product of [2,...9] X [2,...,9].
3. For each {I, J} pair, call io:format/2 on the result.

It is succinct, but it does create the lists first though. So it does
uses some more memory.


-- 
J.



More information about the erlang-questions mailing list