This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] Some suggested improvements to the Graphics and Bigarray modules
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2001-10-11 (08:39) From: John Prevost Subject: Re: [Caml-list] Some suggested improvements to the Graphics and Bigarray modules
```>>>>> "jh" == Jeff Henrikson <jehenrik@yahoo.com> writes:

jh> Also, I find the caml for loop's lack of functionality
jh> annoying.  I really should learn camlp4 so I can write a real
jh> C-style for loop.  (with break and continue, though it's not
jh> pertinent here.)  Somebody doesn't have such things
jh> convieniently lying around do they?

Personally, I use tail loops for this sort of thing.  You could also
use a while loop, but that is less efficient than a for loop or a tail
loop in O'Caml (since you'd have to use refs and break the write
barrier.)  Here's an example:

C code:

int i;
int j;
int count;

/* what does this loop do?  I don't know... */
for ( i = 0, count = 0; i < I_MAX; i++ ) {
for ( j = 0; j < J_MAX; j++ ) {
if ( i == j ) continue;
if ( (i + j) == count ) break;
count++;
}
}
return count;

Caml code:

let rec loop_1 i count =
let rec loop_2 j count =
if i = j then               loop_2 (succ j) count
else if i + j = count then  loop_1 (succ i) count
else                        loop_2 (succ j) (succ count)
in loop_2 0 count
in loop_1 0 0

The caml code is certainly less clear in this case--but I think that's
partialyl because the computation was created just to make a point.
:) One might be able to use a ref for count to make it more clear how
count is "updated".  But it leads to even messier code, and worse
runtime performance.  A "real" loop example would also provide a way
to define better names for the functions than "loop_1" and "loop_2".

The tail calling to continue or break loops makes it easy to duplicate
effects that would be created in C with gotos, since you can only
break or continue the inner loop in C.

With some experience, tail-call loops will come to mind naturally.  I
practically never use the for or while loop constructs in O'Caml.

John.
-------------------
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

```