ocaml - how to break a loop?
hi all,
i need to break a loop under a certain condition in ocaml. as i googled, i learnt there is no way to break a loop.
my problem is as the following:
i have a player's available moves in my array. if user's move is an element of this array, then i will accept it, otherwise reject it.
if i was writing on java, i would do it like:
boolean isMoveValid = false;
for (int i = 0; i < movesArray.length(); i++) {
.. if(movesArray == usersMove) {
.... isMoveValid = true;
.... break;
.. }
}
but i couldn't break the loop in ocaml.
do you have any solution for my purpose?
thanks all.
Hi,
Well, one solution in your case would be to use exceptions.
You first define your exception:
and then:
Well, one solution in your case would be to use exceptions.
You first define your exception:
exception Out_of_loop
and then:
tryfor i = 0 to n do plenty of things; if cond then throw Out_of_loopdone;with Out_of_loop -> ()
I don't know ocaml, but in Scheme that's exactly how it's done (except more likely with recursion). Take a look at call/cc if you're interested.
This will do the trick, and won't use the extra processing and stack time needed to throw and catch an exception. Exceptions in OCaml are somewhat costly, especially if they backtrace through an external C function.
Also, according to my testing, exceptions are less time-costly under the bytecode interpreter than they are in native-compiled executables, but this might be a platform-specific artifact (Debian-based linux). Also, it kind of makes sense... if you're running something through the optimizing compiler, you've already made sure it all works like it is supposed to, and only the expected exceptions (like End_of_file) get thrown under most conditions.
let isValid available made = let idx = ref 0 and invalid = ref true and n = Array.length available in while !invalid && !idx < n do if available.(!idx) = made then invalid := false; incr idx done; not !invalid;;
Also, according to my testing, exceptions are less time-costly under the bytecode interpreter than they are in native-compiled executables, but this might be a platform-specific artifact (Debian-based linux). Also, it kind of makes sense... if you're running something through the optimizing compiler, you've already made sure it all works like it is supposed to, and only the expected exceptions (like End_of_file) get thrown under most conditions.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement