Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck in an infinite loop in a function

I'm stuck in an infinite loop in this function:

let rec showGoatDoorSupport(userChoice, otherGuess, aGame) =                                       
    if( (userChoice != otherGuess) && (List.nth aGame otherGuess == "goat") ) then otherGuess
    else showGoatDoorSupport(userChoice, (Random.int 3), aGame);;

And here's how I'm calling the function:

showGoatDoorSupport(1, 2, ["goat"; "goat"; "car"]);             

In the first condition in the function, I compare the first 2 input parameters (1 and 2) if the are different, and if the item in the list at index "otherGuess" is not equal to "goat", I want to return that otherGuess.

Otherwise, I want to run the function again with a random number between 0-2 as the second input parameter.

The point is to keep trying to run the function until the second parameter doesnt equal the first, and that slot in the List isn't "goat", then return that slot number.

like image 970
Joshua Soileau Avatar asked Sep 27 '12 23:09

Joshua Soileau


2 Answers

Don't use ==, it checks for physical equality. Use =. Two different strings will never be physically equal, even if they contain the same sequence of characters. (This is necessary, because strings are mutable in OCaml.)

$ ocaml
        OCaml version 4.00.0

# "abc" == "abc";;
- : bool = false
# "abc" = "abc";;
- : bool = true
like image 143
Jeffrey Scofield Avatar answered Nov 07 '22 20:11

Jeffrey Scofield


Another to do that is to use the String.compare. An example:

 if String.compare str1 str2 = 0 then (* case equal *)
 else (* case not equal *)
like image 1
Joseph Elcid Avatar answered Nov 07 '22 19:11

Joseph Elcid