当我运行以下代码时,出现语法错误,但据我所知,语法是正确的。这将尝试实现队列结构,其中函数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