【问题标题】:compare two equivalence classes比较两个等价类
【发布时间】:2012-02-15 04:10:07
【问题描述】:

我有这个简单的图表:

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;;

传递闭包矩阵的输出为:

假假假
真真真假
真真真假

函数比较等价类:

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

输出是 raise Not_found

您能帮我解释一下为什么它不能给出正确的顺序吗?谢谢。

【问题讨论】:

    标签: ocaml


    【解决方案1】:

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

    在所有三个反例中,您对string 和int 的顺序有何期望?一个接一个还是一个随机的顺序?由于它们之间没有优势,它们没有可比性,并且您的代码会引发Not_found 异常。

    处理此问题的一种方法是捕获Not_found 异常,并说没有唯一的顺序。或者更温和的方法是只返回 0 而不是引发异常,这意味着您不关心无与伦比的类之间的顺序。

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

    【讨论】:

    • 请不要提出 Not_found - 定义自定义异常。
    • 您能否为我解释一下“它不能给您正确的订单,因为在某些情况下有很多正确的订单”?我想要一个接一个的订单。
    • 您认为由于字典顺序,int 应该在 string 之前。但就等价类而言,它们之间没有顺序。如果有多个订单,请不要尝试找到唯一的订单。如果您坚持,请尝试比较字符串以对其进行排序。但对我来说,这没有意义。
    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2013-08-18
    • 2023-03-30
    • 2013-06-07
    • 2015-02-23
    相关资源
    最近更新 更多