Version française
Home     About     Download     Resources     Contact us    
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: TeXitoi <texitoi+news@t...>
Subject: Re: While loop
Grant Olson <kgo@grant-olson.net> writes:

> On 8/30/10 6:43 PM, Mike Chen 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];;
> 
> # let pp list =
>     let list2 = List.filter (fun x -> x != 5) list in
>     let list3 = List.map (fun x -> x mod 3) list2 in
>     list3;;
> val pp : int list -> int list = <fun>
> # pp [3; 4; 5];;
> - : int list = [0; 1]
> #
> 
> Alternately, if you really want to abort the processing at the first 5,
> you could use pattern-matching to create a new list.  I don't want to
> overwhelm you with too much code if you're just getting started, but you
> should look into it.  But be warned, once you're familiar with
> pattern-matching, most language's case and if statements will seem
> painfully crippled.

Can't resist...

The same thing as yours (using patern matching), and should be more
effective (using List.append in a loop to add one element at the end
is not a good idea for effectiveness) :

# let rec pp = function
    (* if a 5 or the empty list, return the empty list *)
    | 5 :: _ | [] -> []
    (* else mod 3 and recurse on the rest of the list *)
    | x :: xs -> x mod 3 :: pp xs;;
val pp : int list -> int list = <fun>
# pp [3; 4; 5];;
- : int list = [0; 1]

But maybe the beginner list is more appropriate for this kind of
discution.

-- 
Guillaume Pinot                                http://www.texitoi.eu

« Les grandes personnes ne comprennent jamais rien toutes seules, et
c'est fatigant, pour les enfants, de toujours leur donner des
explications... » -- Antoine de Saint-Exupéry, Le Petit Prince

()  ASCII ribbon campaign      -- Against HTML e-mail
/\  http://www.asciiribbon.org -- Against proprietary attachments