Browse thread
[Caml-list] Great Beginner
[
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: | Remi VANICAT <vanicat@l...> |
| Subject: | Re: [Caml-list] Great Beginner |
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