如何使用没有可变数据的循环创建图形?

时间:2014-10-25 00:29:55

标签: ocaml immutability mutual-recursion

我有下一个代码:

module MakeLink (Key : Map.OrderedType) = struct
   module Links = Map.Make (Key)

    type 'a t = 
      { links : 'a t Links.t;
        value : 'a
      }

    type key_t = Key.t

    let make value = 
      { links = Links.empty;
        value
      }

    let link linker ~to':linkable ~by:key = 
      { linker with links = 
        Links.add key linkable linker.links
      } 

   (* some functions for reading here *)
end

如何创建彼此链接的两个链接? 我试过了:

let join a ~with':b ~by:key = 
  let rec a' = link a ~to':b' ~by:key
      and b' = link b ~to':a' ~by:(Key.opposite key) in
  a'

But it's looking like a hen that hatched from their own egg. 我的问题是:如何使用(在OCaml或其他语言中)使用循环(例如:双链表)创建没有可变数据的图形?

1 个答案:

答案 0 :(得分:2)

您可以使用let rec在OCaml中创建循环链接结构。

# type 'a g = { links: 'a g list; value: 'a };;
type 'a g = { links : 'a g list; value : 'a; }
# let rec a = { links = [b]; value = 5; }
      and b = { links = [a]; value = 6; };;
val a : int g =
  {links =
  ... many strange lines of output ...
val b : int g =
  {links =
  ... many more strange lines of output ...

然而,一旦你有了这样的结构,编写能够以有用的方式处理它的函数就非常困难。我不认为你可以用OCaml这种热门的语言进行这种编程。实际上,您必须为链接使用可变字段。

我没有这方面的经验,但似乎更有可能在非渴望的语言Haskell中进行这样的处理。