5

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.

1
  • 1
    looks like c programming habits Commented Sep 29, 2012 at 7:24

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome : ) You are an Ocaml master!
Thanks, though really I'm just a humble practitioner. Ὁ βίος βραχύς, ἡ δὲ τέχνη μακρή -- Life is short, the craft is long.
Along the exact same line, != should not be used here, the structural difference operator is <> -- though it doesn't make much of a difference on integers.
1

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

1 Comment

there is no such function in stdlib, you probably meant String.compare

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.