[erlang-questions] On Loop

黃耀賢 (Yau-Hsien Huang) g9414002.pccu.edu.tw@REDACTED
Mon Jul 18 10:24:39 CEST 2011


---------- Forwarded message ----------
From: 黃耀賢 (Yau-Hsien Huang) <g9414002.pccu.edu.tw@REDACTED>
Date: 2011/7/18
Subject: Re: [erlang-questions] On Loop
To: Jesper Louis Andersen <jesper.louis.andersen@REDACTED>


2011/7/18 Jesper Louis Andersen <jesper.louis.andersen@REDACTED>

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

Yes, and my question is: did I save memory by using nested loop?

By using for/4, it may be a
    for(1, fun fp/1, fun fi/1, fun fc/1)
where fp/1 is
    fp(I) -> I =< 81.

When it's nested loop,
    main() -> for(1, fun fp/1, fun fi/1, fun fc/1).
    fp(I) -> I =< 9.
    ...
    fc(I) -> for (1, fun fp/1, fun fi/1, fc1(I)).
    fc1(I) -> fun(J) -> io:format("~w x ~w = ~w~n", [I, J, I*J]) end.

Did I save memory when main/0 only run a function doing recursion
9 times, while in each time recursion it wakes up another function,
fc/1, recurring 9 times?

Following the consideration, can we say, "keep your Erlang program
flat," that is, when executing there're not many too deep recursion
and it's worth memory-restrict machines?

-- 

Best Regards.

--- Y-H. H.





-- 

Best Regards.

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


More information about the erlang-questions mailing list