有没有更好的方法来构建这样的优先级队列?

时间:2013-03-12 20:13:10

标签: tree functional-programming ocaml priority-queue

我已经实现了优先级队列,效果很好。以下是我的类型定义。

type 'a t = | Leaf of ('a -> 'a -> int)
            | Node of 'a * 'a t * 'a t * ('a -> 'a -> int)

我的想法是树采用比较器功能('a - >'a - > int)并产生'a t,它将由比较器排序。
但是,我在每个Leaf和Node上都有比较器,我想知道是否有更好的方法 具体来说,给定一棵树,我希望能够轻松访问其比较器。而且我不知道如果没有在树的每个Node和Leaf上使用比较器,我是否可以这样做。

由于

1 个答案:

答案 0 :(得分:4)

解决这个问题的标准方法是编写一个给出的仿函数 包含PQ中包含的类型的模块+比较 您给出的函数返回一个专门用于该类型的新PQ模块 和比较功能。

module PriorityQueue (OT : Map.OrderedType) = struct
  type t = 
    | Leaf
    | Node of OT.t * t * t
  (*Define your functions in terms of OT.compare ...*)
end

然后,您将使用

创建具体的PriorityQueue模块
module FunnyPQ = PriorityQueue(struct
  type t = int
  let compare _ _ = pred (Random.int 3)
end)

请参阅OrderedType的定义:http://caml.inria.fr/pub/docs/manual-ocaml-4.00/libref/Map.OrderedType.html

您当然也可以使用您采用的方法,但要考虑因素 数据类型按以下方式分为2种类型

type 'a pq = 
  | Leaf
  | Node of 'a * 'a pq * 'a pq

type 'a t = { 
  comp : 'a -> 'a -> int ;
  pq : 'a pq
}

请注意,使用此方法会丢失某些类型的安全性,因为现在如果您正在使用例如'a pq -> 'a pq -> 'a pq之类的签名编写函数,则无法保证第一个pq参数和第二个pq参数是使用相同的方式构造的比较功能。

相关问题