當我運行以下代碼時,出現語法錯誤,但據我所知,語法是正確的。這將嘗試實現隊列結構,其中函數from_list
將列表轉換爲具有相應值的隊列。我寫了str_of_int_q
來打印隊列的內容。 x
和y
應該是兩個節點,頭部爲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指示<-
。但是我將一個適當類型的對象存儲到一個可變字段中,所以我沒有看到發生了什麼問題。
如果你把';;'放在'x.next'之前,它會起作用嗎? – melpomene
@melpomene呃,當我把';;'放在'x.next'之前,然後把';'從結尾處拿出來的時候。我不明白爲什麼會這樣,但很高興看到它的確如此。把這個作爲答案,我會接受它。 – Addem