2017-10-10 85 views
0

當我運行以下代碼時,出現語法錯誤,但據我所知,語法是正確的。這將嘗試實現隊列結構,其中函數from_list將列表轉換爲具有相應值的隊列。我寫了str_of_int_q來打印隊列的內容。 xy應該是兩個節點,頭部爲x,尾部爲y更改OCaml中的可變字段

;; open Assert 

type 'a qnode = {v: 'a; 
       mutable next: 'a qnode option} 
type 'a queue = {mutable head: 'a qnode option; 
       mutable tail: 'a qnode option} 

let from_list (l: 'a list) : 'a queue = 
    let rec loop (l2: 'a list) (qu: 'a queue) = 
    begin match l2 with 
    | [] -> qu 
    | [x] -> let y = {v = x; next = None} in 
      qu.head <- Some y; qu.tail <- Some y; 
      qu 
    | h1::h2::t -> let y = qu.head in 
        let z = {v = h1; next = y} in 
        qu.head <- Some z; 
        qu 
    end 
    in loop l {head = None; tail = None} 

let str_of_int_q (q: int queue) : string = 
    let rec loop (r: int qnode option) (s: string) : string = 
    begin match r with 
    | None -> s 
    | Some n -> loop n.next (s^(string_of_int n.v)) 
    end 
    in loop q.head "" 

let x = {v = 1; next = None} 
let y = {v = 2; next = None} 
x.next <- Some y; 
let z = {head = Some x; tail = Some y} 
;; print_endline (str_of_int_q z) 

我的錯誤:32

line 32, characters 7-9: 
Error: Syntax error 

行是行x.next <- Some y;和字符7-9指示<-。但是我將一個適當類型的對象存儲到一個可變字段中,所以我沒有看到發生了什麼問題。

+0

如果你把';;'放在'x.next'之前,它會起作用嗎? – melpomene

+0

@melpomene呃,當我把';;'放在'x.next'之前,然後把';'從結尾處拿出來的時候。我不明白爲什麼會這樣,但很高興看到它的確如此。把這個作爲答案,我會接受它。 – Addem

回答

2

OCaml中的頂級語句由;;分隔。但是,;;在幾個關鍵字之前是可選的,例如let,open,type等。這就是爲什麼大多數時候您不需要;;

在你的情況下,需要;;來消除let y = {v = 2; next = None}x.next <- Some y之間的歧義。後者是一個表達式,並不以特殊關鍵字開頭,所以OCaml不知道在這裏插入隱式;;。請參閱http://ocaml.org/learn/tutorials/structure_of_ocaml_programs.html#The-disappearance-of

正如所解釋的存在,你可以因爲通過引入一個虛擬的結合,我們開始我們的語句let,再次做歧義消除

let y = {v = 2; next = None} 
;; x.next <- Some y 

let y = {v = 2; next = None} 
let() = x.next <- Some y 

這後一種解決方案工作。

注意:我也從代碼中刪除了尾隨的;;actually an infix operator,它組合了兩個表達式(通過拋出第一個表達式的結果並返回第二個表達式的結果)。這不是你想要的。