Browse thread
adding lots of elements to a list
-
julien.michel@e...
- Jonathan Roewen
- Shawn
- Nils Gesbert
- Jon Harrop
[
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: | Jonathan Roewen <jonathan.roewen@g...> |
| Subject: | Re: [Caml-list] adding lots of elements to a list |
> 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) ;; The let in the function is local, so is completely different to the global list value. You'd want to use a ref. let list = ref [];; while ... do list := !list @ [!count]; done (* btw, the output proves you're not adding to the global list, as the head of the list should never change, as you're concatenating to the end of the list *) (* as a further aside, concatenating two lists takes time proportional to the length of the first argument (your global list). prepending is faster, though ends up with a reversed list, as in: list := !count :: !list *) > 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; *** 'list = [!count] @ list' is a boolean equation. It in fact tests if list is structurally equivalent to [!count] @ list, and generates the value false, which is then discarded. Since list is never modified, it is always empty, thus List.hd will raise the exception you have witnessed. > But this time I get a "Warning S: this expression (list = [!count]@list ;) > should have type unit." Yes, this is what I meant by the boolean equation -- it's return type is bool, not unit. Jonathan