5

我在这个函数中陷入了无限循环:

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

这是我调用函数的方式:

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

在函数的第一个条件中,我比较前 2 个输入参数(1 和 2)是否不同,并且如果列表中索引“otherGuess”的项目不等于“goat”,我想返回那个其他猜。

否则,我想使用 0-2 之间的随机数作为第二个输入参数再次运行该函数。

关键是继续尝试运行该函数,直到第二个参数不等于第一个参数,并且列表中的那个槽不是“山羊”,然后返回那个槽号。

4

2 回答 2

8

不要使用==,它会检查物理平等。使用=. 两个不同的字符串在物理上永远不会相等,即使它们包含相同的字符序列。(这是必要的,因为字符串在 OCaml 中是可变的。)

$ ocaml
        OCaml version 4.00.0

# "abc" == "abc";;
- : bool = false
# "abc" = "abc";;
- : bool = true
于 2012-09-27T23:23:05.123 回答
1

另一种方法是使用String.compare. 一个例子:

 if String.compare str1 str2 = 0 then (* case equal *)
 else (* case not equal *)
于 2012-09-29T07:12:35.043 回答