Jump to content
  • Advertisement
Sign in to follow this  
metalyric

ocaml - how to break a loop?

This topic is 4874 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
Hi,

Well, one solution in your case would be to use exceptions.

You first define your exception:


exception Out_of_loop


and then:


try
for i = 0 to n do
plenty of things;
if cond then throw Out_of_loop
done;
with
Out_of_loop -> ()


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
thank you, using an exception works.

Share this post


Link to post
Share on other sites
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.

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!