From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id MAA11565; Sun, 11 Nov 2001 12:33:30 +0100 (MET) X-Authentication-Warning: pauillac.inria.fr: majordomo set sender to owner-caml-list@pauillac.inria.fr using -f Received: from nez-perce.inria.fr (nez-perce.inria.fr [192.93.2.78]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id MAA11630 for ; Sun, 11 Nov 2001 12:33:29 +0100 (MET) Received: from mel-rti17.wanadoo.fr (smtprt17.wanadoo.fr [193.252.19.228]) by nez-perce.inria.fr (8.11.1/8.10.0) with ESMTP id fABBXS507595 for ; Sun, 11 Nov 2001 12:33:28 +0100 (MET) Received: from antholoma.wanadoo.fr (193.252.19.153) by mel-rti17.wanadoo.fr; 11 Nov 2001 12:33:28 +0100 Received: from debian (217.109.146.219) by antholoma.wanadoo.fr; 11 Nov 2001 12:33:20 +0100 Received: from moi by debian with local (Exim 3.32 #1 (Debian)) id 162sse-0000F2-00 for ; Sun, 11 Nov 2001 12:34:28 +0100 To: caml-list@inria.fr Subject: Re: [Caml-list] Great Beginner References: <3BEBDDCA.1060307@francetelecom.com> From: Remi VANICAT Date: 11 Nov 2001 12:34:28 +0100 In-Reply-To: <3BEBDDCA.1060307@francetelecom.com> Message-ID: <87hes1tubf.dlv@wanadoo.fr> User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.1 MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk Franck writes: > Hi! > > I want to calculate the sum of the n first numbers. > I've written this code: > let x =0;; > let somme n = > for i=1 to n > do > x=x+i > done;; > > It doesn't work. > Why ? Because ocaml is a functional language, so imperative action (as x = x + i) doesn't work. A mean to do this is : let x = ref 0;; let somme n = for i = 1 to n do x := !x + i done;; but the good way to do it is more : let rec somme n = if n = 0 then 0 else n + (somme (n - 1)) let x = somme 10 or even better (with a tail recursive function) : let somme n = let rec aux i x = if i <= n then aux (i+1) (x + i) else x in aux 1 0 -- Rémi Vanicat vanicat@labri.u-bordeaux.fr http://dept-info.labri.u-bordeaux.fr/~vanicat ------------------- Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr