Flux
Flux

Reputation: 10950

How to exit a while loop prematurely

Suppose I have an infinite while loop and I want to exit the loop. What is the proper way to do so? OCaml does not have break, so I might have to raise an exception to terminate the loop (try while true do ... raise My_exception ... done with My_exception -> ()). Is this the idiomatic way to exit infinite loops? Which exception should I raise inside the loop?

Upvotes: 1

Views: 442

Answers (2)

ivg
ivg

Reputation: 35280

Is this the idiomatic way to exit infinite loops?

Yes, it is a rather idiomatic way of exiting from a non-idiomatic infinite loop. There is even a ready to go exception for that, called Exit1, e.g.,

let main () =
  try while true do
      let continue = work () in
      if not continue then raise Exit;
    done
  with Exit -> ()

With that said, the idiomatic and proper way to encode infinite loops is to use recursion. It is not only more legible but also has the natural way of exiting the loop, e.g., the same infinite loop in the functional style,

let rec main () =
  if work () then main ()

1) Though it is better to define your own exception, like @octachron did, to eschew the possibility of clashing with some other code that also relies on this exception.

Upvotes: 6

octachron
octachron

Reputation: 18912

You can use a local exception to make sure that function calls inside your loop are not interfering with your control flow:

let exception Early_exit in
try while ...
   raise Early_exit
done;
...
with Early_exit -> ...

Upvotes: 7

Related Questions