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: Nils Gesbert <nils.gesbert@e...>
Subject: Re: [Caml-list] adding lots of elements to a list
On Fri,  2 Jun 2006 17:28:46 +0200
julien.michel@etu.univ-orleans.fr wrote:

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

What you are doing with this expression is not to modify the list "list" (which you cannot do, because lists are immutable) but to define a new variable, which happens to have the same name "list", whose scope is just the printf expression. So it is not even true that new elements are well added to the local list. You may see better the meaning of this code by using a different identifier for the local variable : your code is equivalent to

let new_list = list@[!count] in Printf.printf "The 1st element is  %i \n" (List.hd new_list)

so the original list is never modified and each iteration creates a new list.

To construct a list step by step, you may either use a reference and a loop or use a recursive function, like this for instance :

let list =
  let rec add_elem list count =
    if count > 0 then add_elem (count::list) (count-1)
    else list
  in add_elem [] 3

By the way, you should construct the list by always adding elements at the head (with the :: constructor) and avoid @, because @ is a function that has to go through the whole list to reach the end, take your new element then reconstruct the whole list (the lists are constructed backwards), whereas adding an element at start is immediate.