[erlang-questions] How to keep adding items to a data structure
Donald Steven
t6sn7gt@REDACTED
Mon Apr 25 12:51:28 CEST 2016
Thanks Raimo, that's very helpful. I hadn't realized that the compiler
would free up resources. I had this vision of neverending piling up.
Best,
Don
On 04/25/2016 06:32 AM, Raimo Niskanen wrote:
> On Sun, Apr 24, 2016 at 05:24:05PM -0400, Donald Steven wrote:
>> Thanks Oliver, I appreciate your note. I understand that a list can
>> contain different elements, as you've indicated. That's wonderful! And
>> I have that book on order. What I'm so frustrated by is, apparently, in
>> order to extend a list by adding new musical events, that I have to keep
>> creating new lists, like:
>>
>> List1 = [musical-event],
>> List2 = List1 ++ [new-musical-event],
>> List3 = List2 ++ [new-musical-event],
>> List4 = List3 ++ [new-musical-event],
>> etc.
>>
>> all the way to perhaps a few thousand. This is primitive and absurd. I
>> need a better solution, whether it's a list or an array or a record.
> Well, if you do it that way you do it the primitive and absurd way.
>
> Lists are single linked and that is a feature. You should add to the head
> of the list since that is the end that is accesible in constant time:
> List1 = [musical_event],
> List2 = [new_musical_event|List1],
> List3 = ...
>
> Regarding the names List1, List2, List3, ... that is a consequence of
> having single assignment variables, which also is a feature. It stems from
> normal mathematical notation where this is gibberish:
> I = I + 1
> You really mean
> I_1 = I_0 + 1
> where _N often is written as a subscript to indicate that these are
> different instances of a variable.
>
> We programmers then after learning imperative programming such as C get
> used to '=' meaning a destructive update of a memory location, which is
> just the kind of low level concept that functional programming wants to
> avoid talking about.
>
> The compiler will figure out that List1 is not used after List 2 = ...
> and hence not keep that value around so you really just prepend to the same
> list and end up with just the last list List4.
>
> But normally you just prepend one item to the head and then iterate through
> recursion so you do not need to name that many instances of a variable
> within one function clause.
>
> I hope that helped somewhat.
More information about the erlang-questions
mailing list