Reputation: 1373
I have this simple graph:
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;;
output of transitive closure matrix is:
false false false
true true true
true true true
function compare equivalence classes:
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);;
functions compute equivalence classes:
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)
it gives me the order: label, name, string
, mean correct order.
The problem is that, when I test with another graph, for example:
name -> string
^
|
v
label -> int
or
name -> int
^ \
| \
v v
label string
or
name -> string
|
v
label -> int
the output is raise Not_found
Could you please help me to explain why it cannot give the right order? Thank you.
Upvotes: 2
Views: 191
Reputation: 41290
As I said in previous thread, it cannot give you the right order because in some cases there are a lot of right orders.
In all three counterexamples, what would you expect regarding the order of string
and int
? One after another or just a random order? Since there is no edge between them, they are not comparable and your code raises Not_found
exception.
One way to deal with this problem is catching Not_found
exception, and saying that there's no unique order. Or an gentler way is just returning 0
instead of raising exception which means you don't care about the order between incomparable classes.
As @ygrek said in the comment, using a built-in exception is a bad idea. You should define a custom exception dedicated to your purpose.
Upvotes: 2