Browse thread
adding lots of elements to a list
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Shawn <shawnw@s...> |
| Subject: | Re: [Caml-list] adding lots of elements to a list |
julien.michel@etu.univ-orleans.fr wrote:
> Can someone advise me a better way to do what I want ?
>
>
Lists sound like the best choice for now. If memory becomes a problem, a
disk-based db like gdbm might be an alternative. But until you /know/
that the lists are a bottleneck, don't bother.
>
> 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
>
You're creating a new binding named list each time you do let list =
..., not updating an existing one. Outside of the while loop, the fir
st, outer one is what's visible and used. You need references:
...
let list = ref []
...
while !count > 0 do
...
list := !count :: !list
....
done
Also, avoid appending to the list like you do if it's going to be big,
as doing so will cause a lot of extra work for the garbage collector.
Alternatively, do away with the while, and use a recursive function, and
eliminate the need for references at all. Something like:
let rec count_list count lst =
let count = count - 1 in
if count > 0 then count_list count (count :: lst) else lst
let list = count_list 3 []