Newbie question on arrays and indexing

martin j logan <>
Thu Mar 20 19:27:16 CET 2003


On Thu, 2003-03-20 at 12:01, Webb Sprague wrote:
> Hi Everybody,
> 
> I am afraid this is just a stupid question, so if it is, please be nice 
> and point me to some documentation...  :)

You don't have to worry about juvenile flames on this list. 

> 
> I am wondering what is the best way to handle indexing into a list or 
> tuple.  The issue at hand is that I want to play around with virtual 
> clocks, as per Garg 2001, but all the algorithms are in terms of 
> indexing using integers, like Matrix[3,4].
> 
The best way, the only way as far as I know, to deal with indexing into
a list is to iterate though it. something like

itterate(2, List) 

to get the second element.
    
itterate(Count, [H|T]) ->
    itterate(Count -1, T);
itterate(1, [H|T]) ->
    H;
itterate(Count, []) ->
    exit({error, outofbounds}).

or you could use 

stdlib:
lists:nth(N, List) -> Element

There are a few other ways to do this. Lists are quite fast but if you
are really concerned about speed you might want to try using some other
structure. Tuples might be better if you know how many elements you are
going to need before hand. To index a tuple use element(N, Tuple) this
can be found in the kernel module "erlang". Good Luck

Cheers,
Martin

> Thanks
> Webb
> 





More information about the erlang-questions mailing list