Version franÁaise
Home ††† About ††† Download ††† Resources ††† Contact us †††
Browse thread
[Caml-list] OCaml Speed for Block Convolutions
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: JudicaŽl Courant <Judicael.Courant@l...>
Subject: Re: [Caml-list] should "a.(i)" be a reference? (was "let mutable")
Hi,

On Fri, 8 Jun 2001 21:30:29 +0200
Michel Quercia <michel.quercia@prepas.org> wrote:

> (* same, but with a for loop *)
> let add_1 a =
>   let res = ref 0 in
>   for i=0 to Array.length(a)-1 do res := !res + a.(i) done;
>   !res
> ;;
> 
> No exclam and no ref for i ?  And its value is changing though ? Where
is 
> gone the logic ?

It does not change more than in "List.iter (fun i -> res := !res + a(i))
l". The "for" loop is just a new kind of binder. With the suitable
for_loop function (let rec for_loop b e f = if b <= e then begin f b;
for_loop (b+1) e f end), you could write this as:

for_loop 0 (Array.length(a)-1) (fun i -> res := !res + a.(i))

On the contrary, a mutable "i" would mean you could change the way the
iterations are done inside your loop, which is not really nice IMHO:

for i:= 0 to Array.length(a)-1 do
 res := !res+a.(!i);
 if once_again() then i := !i - 1
done

is really bad programming style; if you want to do this, use a while loop
instead.

> 
> > This construction would have introduced the notion of
> > Lvalue in Caml, thus introducing some additional semantics complexity,
> > and a new notion to explain to beginners.
> 
> Lvalues already exist in Ocaml (and have to be explained to beginners),
for 
> example : "a.(i) <- a.(i)+1".
> 

You are right, but maybe this suggest that a.(i) should be typed as a
reference?

Or, in order to preserve compatibility, the reference could be noted
"a.&(i)"; "a.(i)" would be just syntactic sugar for
"!a.&(i)" and "a.(i) <- y" would be syntactic sugar for "a.&(i) := y".
The same could be done for mutable record fields. This would not only tidy
the semantics, but it would also enrich the language: the programmer could
then use references to mutable record fields or to array cells as function
arguments (would anybody be interested by such a feature?).

Best regards,

JudicaŽl Courant.
-- 
Judicael.Courant@lri.fr, http://www.lri.fr/~jcourant/
(+33) (0)1 69 15 64 85
-------------------
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