比较两个等价类

时间:2012-02-15 04:10:07

标签: ocaml

我有这个简单的图表:

name -> string
 ^
 |
 v
label

let matrix = [|
[|false; false; false |];  
[|true; false; true  |];
[|false; true; false|] |]

(* compute transitive closure of matrix*)
let transClosure m =
  let n = Array.length m in
  for k = 0 to n - 1 do
    let mk = m.(k) in
    for i = 0 to n - 1 do
      let mi = m.(i) in
      for j = 0 to n - 1 do
    mi.(j) <- max mi.(j) (min mi.(k) mk.(j))
      done;
    done;
  done;
  m;;

传递闭包矩阵的输出是:

false false false
真的是真的 真的是真的

函数比较等价类:

let cmp_classes m i j =
  match m.(i).(j), m.(j).(i) with
      (* same class: there is a path between i and j, and between j and i *)
    | true, true -> 0
      (* there is a path between i and j *)
    | true, false -> -1
      (* there is a path between j and i *)
    | false, true -> 1
      (* i and j are not compareable *)
    | false, false -> raise Not_found

let sort_eq_classes m = List.sort (cmp_classes m);;

函数计算等价类:

let eq_class m i =
  let column = m.(i)
  and set = ref [] in
  Array.iteri begin fun j _ ->
    if j = i || column.(j) && m.(j).(i) then
      set := j :: !set
  end column;
  !set;;

let eq_classes m =
  let classes = ref [] in
  Array.iteri begin fun e _ ->
    if not (List.exists (List.mem e) !classes) then
      classes := eq_class m e :: !classes
  end m;
  !classes;;

(* compute transitive closure of given matrix *)
let tc_xsds = transClosure matrix
(* finding equivalence classes in transitive closure matrix *)
let eq_xsds = eq_classes tc_xsds
(* sorting all equivalence classes with transitive closure matrix *)
let sort_eq_xsds = sort_eq_classes tc_xsds (List.flatten eq_xsds)

它给我订单:label, name, string,表示正确的顺序。

问题是,当我用另一个图测试时,例如:

name -> string
 ^
 |
 v
label -> int

name -> int
^   \
|    \
v     v
label string

name -> string
|
v
label -> int

输出提升Not_found

请你帮我解释为什么它不能给出正确的订单?谢谢。

1 个答案:

答案 0 :(得分:2)

正如我在previous thread所说,它无法给你正确的订单,因为在某些情况下会有很多正确的订单。

在所有三个反例中,您对stringint的顺序有何看法?一个接一个或只是一个随机的订单?由于它们之间没有边缘,因此它们不具有可比性,并且您的代码会引发Not_found异常。

解决此问题的一种方法是捕获Not_found异常,并说没有唯一的顺序。或者更温和的方式就是返回0而不是引发异常,这意味着你不关心无法比较的类之间的顺序。

正如@ygrek在评论中所说,使用内置异常是一个坏主意。您应该定义专门用于您目的的自定义异常。