Functional programming 卡在函数的无限循环中
我被困在这个函数的无限循环中:Functional programming 卡在函数的无限循环中,functional-programming,ocaml,Functional Programming,Ocaml,我被困在这个函数的无限循环中: let rec showGoatDoorSupport(userChoice, otherGuess, aGame) = if( (userChoice != otherGuess) && (List.nth aGame otherGuess == "goat") ) then otherGuess else showGoatDoorSupport(use
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"]);
下面是我调用函数的方式:
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"]);
在函数的第一个条件中,我比较前两个输入参数(1和2),如果参数不同,并且如果索引“otherGuess”处的列表中的项不等于“goat”,我想返回该otherGuess
否则,我想使用0-2之间的随机数作为第二个输入参数再次运行该函数
关键是要一直尝试运行函数,直到第二个参数不等于第一个参数,并且列表中的插槽不是“goat”,然后返回插槽号。不要使用
==
,它会检查物理相等性。使用=
。两个不同的字符串在物理上永远不会相等,即使它们包含相同的字符序列。(这是必要的,因为字符串在OCaml中是可变的。)
另一种方法是使用
字符串。比较。例如:
if String.compare str1 str2 = 0 then (* case equal *)
else (* case not equal *)
真棒:)你是Ocaml大师!谢谢,虽然我只是一个谦虚的实践者。Ὁ βίος βραχύς, ἡ δὲ τέχνημακρή——寿命短,工艺长。沿着完全相同的路线,=这里不应该使用code>,结构差分运算符是
——尽管它对整数没有多大影响。看起来像c
编程习惯stdlib中没有这样的函数,您可能指的是字符串。比较