如何在ocaml中附加两个可变列表

how to append two mutable lists in ocaml

type 'a mylist = 'a listcell ref
and 'a listcell = Nil | Cons of 'a * ('a mylist)

let l1 = (ref (Cons (1, ref (Cons (2,ref Nil)))))
let l2 = (ref (Cons(3, ref (Cons(4, ref Nil)))))

let rec append l1 l2 =
match l1 with
 | {contents = Nil} -> (l1 := !l2; l1)
 | {contents = Cons(h,t)} -> append t l2

这就是我目前所掌握的,目标是将 l2 附加到 l1 我可以遍历到 l1 的末尾并将 ref 替换为 l2 ... 这就是我想要做的。但出于某种原因我失去了一切 在那之前。

任何帮助将不胜感激,谢谢

当您通过递归调用到达列表末尾时,l1 引用第一个列表的 Nil 元素,而不是第一个列表的开头。

您可以通过在 append 中使用辅助函数来解决此问题,它的工作方式与您当前的 append 函数类似。但最后它 returns 来自外部 append 函数的原始 l1