[erlang-questions] Arrays and setelement

Julian Fondren <>
Fri Dec 29 03:56:14 CET 2006


(sorry for any duplicates sent of this.)

I don't know about VM cleverness, but as for the compactness of
tuples (you confused me with talk of 'arrays'), see this
erl_interface prototype for a function that produces them:

  ETERM *erl_mk_tuple(ETERM**,int);

For something more transportable and also clearly compact, with
O(1) random assignment and fetching, you might try something like
the following (just hacked up, seems fine, not very well
commented).

Cheers,
Julian


-module(arrays).
-export([new/1, new/2, new/3, get/2, put/3, size/1, elt_width/1]).

new(Size) -> new(Size,0,32).
new(Size,Init) -> new(Size,Init,32).
new(Size,Init,Width) when Size > 0, Width > 8, Width rem 8 == 0 ->
    new(Size,Init,Width,<<>>).
new(0,_,W,B) -> <<W:32, B/binary>>;
new(N,I,W,B) -> new(N-1,I,W,<<I:W, B/binary>>).

get(N,<<W:32,B/binary>>) when N > 0 ->
    Before = W * (N - 1),
    <<_:Before, X:W, _/binary>> = B,
    X.

put(N,X,<<W:32,B/binary>>) when N > 0 ->
    Before = W * (N - 1),
    <<Bef:Before, _:W, After/binary>> = B,
    <<W:32, Bef:Before, X:W, After/binary>>.

size(<<W:32, B/binary>>) ->
    erlang:size(B) div (W div 8).

elt_width(<<W:32, _/binary>>) -> W.

On 12/28/06, Joel Reymont <> wrote:
> Folks,
>
> According to the setelement docs, it returns an array that is a copy
> of the original, with the element at index N replaced with new value.
> How is this implemented in the VM, though?
>
> Does setelement actually allocate a new array of the same size?
>
> What is the most efficient (speed-wise) implementation of arrays in
> Erlang?
>
> My arrays themselves would be very small, less than 100 elements. I
> do need very fast assignment and fetching, though. The arrays are
> dense, no holes.
>
> 	Thanks, Joel
>
> --
> http://wagerlabs.com/
>
>
>
>
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list