2014-06-05 26 views
0

我開始學習ocaml的,我不明白爲什麼這樣循環下去:鬧掰了一個循環

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

我缺少什麼?

回答

2

這是因爲OCaml讓綁定是不可變的。這個確切的問題是ocaml.org教程中的discussed in detail。使用REF代替,並設置和使用!:=獲得其持有的價值:

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

一個原因,研究OCaml的是學會如何計算與不變的值。下面是一個不依賴於一個可變變量的一個版本:

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

訣竅是重新設想的可變值作爲函數的參數,這使得他們有不同的價值觀不同的時間。

1

最好運行ocaml警告和嚴格的序列來檢測問題。例如

$ 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是否是虛假或不,不這樣做的任務。