Version française
Home     About     Download     Resources     Contact us    
Browse thread
adding lots of elements to a list
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: julien.michel@e...
Subject: adding lots of elements to a list
An application creates as many instances of a class as they are iterations in a
while-loop. 
I would like to store these objects once they are created, at each loop, in
order to operates on them later (to sort, to filter some elements etc...)
For example I would like to add each new instance to a list of object of this
class. 

The number of created objects can grow very fast, and may raise an amount
greater than 100 000 elements. 


At the beginning, I choose to store them in a list, because we can add/delete
elements without wondering about size problem... Actually, in my application, I
can not know how many elements I will add. So It is quite difficult to use arrays.
 
On the other hand, I heard there were some problems with lists wich are very long...

Can someone advise me a better way to do what I want ? 



By the way, I have some difficulties to simply add a new element to the same
list, each time I enter in a while-loop:

let count = ref 3 ;;    (* number of iteration *)
let list = [] in

while (!count > 0)  do
  decr count;
  let list = list@[!count] in
  Printf.printf "The 1st element is  %i \n" (List.hd list) ;
done;

Printf.printf "list contains %i elements \n" (List.length list) ;;


Here is the result after running the program:
The 1st element is  2
The 1st element is  1
The 1st element is  0
list contains 0 elements

The first 3 lines show that new elements are well added to the "local" list,
inside the loop but we can not access to the list outside the while loop,
according to the last line.

I try to declare "list" as a global variable:

let count = ref 3 ;;
let list = [] ;;

while (!count > 0)  do
  decr count;
  list = [!count]@list ;
  Printf.printf "The 1st element is  %i \n" (List.hd list) ;
done;

Printf.printf "list contains %i elements \n" (List.length list) ;;


But this time I get a "Warning S: this expression (list = [!count]@list ;)
should have type unit."
and I get the following error while running the program:
Fatal error: exception Failure("hd")
It seems that no elements are added to the list, which remains empty.

I hope this trivial question won't bother too much people...


Thank you all




-- 
MICHEL Julien
Elève Ingénieur 5ème année Polytech'Orléans
filière Electronique-Signaux-Images (ESI)
spécialité Systèmes Embarqués (SE)

200 Rue Ardoux
Bat A, appt 43
45160
OLIVET