Search code examples
while-loopocamlinfinite-scroll

OCaml : Infinite Loop


I am trying to do this simple while loop but it's not working. The compiler is not giving any type of error or warning but when i try to run my function it ends up in an infinite loop:

let example x =
  let k = ref x in 
  while (!k > 42) do
    if ( (!k mod 5) == 0) then (
      k:= !k/2
    );
  done;
 if(!k<42) then (
   Printf.printf "k is less than 42"  
  );
  if(!k == 42) then (
    Printf.printf "k is equal to 42" 
  )
;;


Solution

  • Well, your loop only modifies !k when !k mod 5 = 0. If !k isn't divisible by 5, it will never change in value. This suggests that the loop will either run 0 times or will run an infinite number of times.

    You don't show any calls to example, but any call where you pass a value > 42 and not a multiple of 5 should loop infinitely it seems to me.

    By the way, this is what @user2864740 was trying to point out. 43 is a value > 42 that's not divisible by 5.

    (As a side comment, you should use = to compare values for equality. The == operator in OCaml is useful in limited cases. This often causes problems for people coming from other languages.)