From: Remi VANICAT <vanicat@labri.u-bordeaux.fr>
To: caml-list@inria.fr
Subject: Re: [Caml-list] Great Beginner
Date: 11 Nov 2001 12:34:28 +0100 [thread overview]
Message-ID: <87hes1tubf.dlv@wanadoo.fr> (raw)
In-Reply-To: <3BEBDDCA.1060307@francetelecom.com>
Franck <franck.collineau@francetelecom.com> 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
next prev parent reply other threads:[~2001-11-11 11:33 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2001-11-09 13:44 Franck
2001-11-11 11:34 ` Remi VANICAT [this message]
2001-11-10 15:29 ` Diego Olivier Fernandez Pons
2001-11-12 6:39 ` Remi VANICAT
2001-11-12 8:13 ` Diego Olivier Fernandez Pons
-- strict thread matches above, loose matches on Subject: below --
2001-11-09 14:10 Krishnaswami, Neel
2001-11-09 11:08 Franck
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=87hes1tubf.dlv@wanadoo.fr \
--to=vanicat@labri.u-bordeaux.fr \
--cc=caml-list@inria.fr \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox