Home     About     Download     Resources     Contact us

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

Browse thread
Re: Instruction return
• Dwight VandenBerghe
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 1997-06-02 (21:20) From: Dwight VandenBerghe Subject: Re: Instruction return
```(I apologize for no French version)

> let rech x v =
>  let n = vect_length v in
>  for i=0 to n-1 do
>   if v.(i) = x then return true
>  done; false;;

This is one of the two main control problems with functional programming,
IMHO.
The solution I use is:

exception Found_it
let rech x v =
try
for i = 0 to pred (vect_length v) do
if v.(i) = x then raise Found_it
done;
false
with Found_it -> true

You don't have to assign vect_length v to n; it is only evaluated once
anyway.
If iter is defined on the type of v, then you can also use

let rech x v =
try
let f x1 = if x1 = x then raise Found_it in
iter f v;  false
with Found_it -> true

The other control problem is when you want the equivalent of:

x = foo(a);
bar();
return x;

If you try

let x = foo(a) in
bar();
x

then bar gets done first, instead of second.  I use this instead:

let f x = bar(); x in
in f (foo a)

I haven't found any other serious problems with Caml's logic flow.  These
two just take some getting used to.

Dwight

```