[erlang-questions] Arrays and setelement

Joel Reymont joelr1@REDACTED
Fri Dec 29 03:59:20 CET 2006


Julian,

Thanks for the tip with binaries. Wouldn't the VM copy these in the  
put function, though?

Would running the hybrid VM help here or wouldn't make a difference  
since there's no message passing?

	Thanks, Joel

On Dec 29, 2006, at 2:54 AM, Julian Fondren wrote:

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

--
http://wagerlabs.com/








More information about the erlang-questions mailing list