2

我不确定如何从可变类型列表中删除循环:

type 'a m_list = Nil | Cons of 'a * (('a m_list) ref)

例如,如果我有一个列表 3,2,2,1,2,1,2,1,..... 我想要一个 3,2,2,1。
我想不通的是初始循环的位置——我有一个看起来像这样的递归,但我不知道如何将它包装成一个递归函数;显然在这里它只会检查前几个术语。

let remove list : unit =
  if is_cyclic list then match list with
    |Nil->()
    |Cons(_,v)-> match (!v) with
      |Nil->()
      |Cons(_,x)->match (!x) with
        |Nil->()
        |Cons(_,y)->match (!y) with
          |Nil->()
          |Cons(_,p) -> if is_cyclic (!p) then p:=Nil else ()

我有一个 is_cyclic 函数,它告诉我 m_list 是否有循环。我想以破坏性方式(更新参考)或非破坏性方式(创建新列表)来执行此操作。

谢谢!

4

2 回答 2

3

根据Pascal Cuoq对您上一个问题的回答,您可以尝试这样的事情:

let rec recurse list already_visited =
  match list with
    Nil -> ()
  | Cons(h, t) -> 
    if List.memq !t already_visited
    then t := Nil          
    else recurse !t (t :: already_visited)

let remove_cycles list = recurse list []

这将遍历列表,直到它到达末尾或访问一个元素两次。当后者发生时,它将最后访问的引用设置为Nil.

如果您有非常大的列表,您可能希望already_visited用另一个数据结构替换。

于 2011-04-01T17:12:16.540 回答
2

如果您没有足够的内存来存储每个先前访问过的元素,则可以改为使用循环检测算法来查找循环中的元素,然后使用它找到循环的结尾并覆盖它的下一个引用。

为此,请修改is_cyclic为返回 a'a mlist ref而不是 a bool。假设它可能在循环中间返回一个元素,遍历原始列表并检查每个元素是否在循环中。这将为您提供循环中的第一个元素。

从那里很容易找到循环的结束 - 只需循环循环直到回到开始。

像这样的东西:

let rec in_cycle x st cyc =
if cyc == x then true
else
    match !cyc with Nil -> false
    | Cons(_, t) when t == st -> false
    | Cons(_, t) -> in_cycle x st t

let rec find_start l cyc =
    if in_cycle l cyc cyc then l
    else
        match !l with Nil -> raise Not_found
        | Cons(_, t) -> find_start t cyc

let rec find_end st cyc =
    match !cyc with Nil -> raise Not_found
    | Cons(_, t) ->
        if t == st then cyc
        else find_end st t

(* ... *)
let cyc = is_cyclic list in
let st = find_start list cyc in
let e = (find_end st cyc) in
match !e with Nil -> failwith "Error"
| Cons(v, _) -> e := Cons(v, ref Nil)
于 2011-04-01T18:24:10.333 回答