简体   繁体   中英

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.

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

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 *)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM