[erlang-questions] Clueless am I

Richard A. O'Keefe ok@REDACTED
Tue Apr 26 07:25:57 CEST 2016



On 26/04/16 7:15 AM, Donald Steven wrote:
> Dear friends,
>
> Please forgive me for being clueless.  (I'm sure it's because I come 
> to Erlang steeped in C.)
> %% THIS DOES NOT WORK
>
> -module(arraytest).
> -export([main/0]).
>
> main() ->
>
>     A1 = array:set(0, nextevent(), array:new(20)),
>     array:set(1, nextevent(), A1),
>     array:set(2, nextevent(), A1),
>     array:set(3, nextevent(), A1),
>     array:set(4, nextevent(), A1),
>
>     io:format("~nArray: ~p~n", [A1]),
>     io:format("Array size: ~p~n~n", [array:size(A1)]).


Erlang has no mutable data structures.
Once you have given A1 a value, that value can never change.
When you call array:set(1, nextevent(), A1),
you pass three immutable values.
array:set/3 responds by creating and returning a NEW value,
which typically reuses bits of its inputs (without changing them
in any way).  So

main() ->
     A0 = array:new(20),
     A1 = array:set(0, nextevent(), A0),
     A2 = array:set(1, nextevent(), A1),
     A3 = array:set(2, nextevent(), A2),
     A4 = array:set(3, nextevent(), A3),
     A5 = array:set(4, nextevent(), A4),
     io:format("Array: ~p~n", [A5]),
     io:format("Array size: ~p~n", [array:size(A5)]).

This is absolutely basic to Erlang, and is one of the reasons why Erlang
is one of the very few languages in which exception handling is worth
anything: no matter what went wrong, your data structures CANNOT have
been corrupted.

Of course you don't want to write a whole list of updates like that,
which is why you would write

     A5 = lists:foldl(fun (N, A) -> array:set(N, nextevent(), A end,
                array:new(20), lists:seq(0, 4))

producing the output

{array,20,0,undefined,
        {{0,1,4,9,16,undefined,undefined,undefined,undefined,
          undefined},
         10,10,10,10,10,10,10,10,10,10}}




More information about the erlang-questions mailing list