麻烦突破循环

时间:2014-06-05 16:29:04

标签: ocaml

我开始学习OCaml,我不明白为什么这会无限循环:

let x = true in
while x do
    print_string "test";
    x = false;
done;;

我错过了什么?

3 个答案:

答案 0 :(得分:4)

研究OCaml的一个原因是学习如何使用不可变值进行计算。这是一个不依赖于可变变量的版本:

let rec loop x =
    if x then
        begin
        print_string "test";
        loop false
        end
in
loop true

诀窍是将可变值重新设想为函数参数,这允许它们具有不同的不同值。

答案 1 :(得分:2)

这是因为OCaml允许绑定是不可变的。这个问题在ocaml.org教程中是discussed in detail。请改用ref,并使用!:=设置并获取它所拥有的值:

let x = ref true in 
    while !x do
        print_string "test";
        x := false
    done;;

答案 2 :(得分:1)

最好运行带有警告和严格序列的ocaml来检测问题。 e.g。

$ ocaml -strict-sequence -w A
    OCaml version 4.01.0

# let x = true in
  while x do
    print_string "test";
    x = false;
  done;;      
Error: This expression has type bool but an expression was expected of type
     unit

这显示了问题:x = false正在测试x是否为假,没有做任务。

相关问题