English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    
Browse thread
While loop
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Shawn Wagner <shawnw@s...>
Subject: Re: [Caml-list] While loop
On Mon, 30 Aug 2010 15:43:40 -0700
Mike Chen <mickey.chuen@gmail.com> wrote:

> Hi,
> 
> I am a caml rookie, and I need your help.
> 
> (* pp is a very simple function *)
> # let pp list =
> 	let newList = ref [] in
> 	let i = ref 0 in
> 	let ele = ref (List.nth list !i) in
> 	while (!ele) != 5 do
> 		newList := List.append !newList [(!ele mod 3)];
> 		i := !i + 1;
> 	done;
> 	!newList;;
> val pp : int list -> int list = <fun>
> 
> # pp [ 3; 4; 5];;
> 
> (* it seems it goes into a forever loop, but I expect it returns [ 0;
> 1]. What is wrong? *)
> 

You never update the value of ele, and so the only way the loop
conditional can ever be false is if the list you pass to the function
starts with a 5.

-- 
Shawn Wagner
shawnw@speakeasy.org