I want to write a function, and I want to learn about clarify and describe by words (analysis) the code before I am going to write it.
So here is a function I want to write: compare two equivalence classes using boolean matrix
I have a boolean matrix, 2 equivalence classes are an input they are a list of int. The output is the compare of two equivalence classes.
The conditions to compare 2 list equivalence classes:
1) boolean matrix is an transitive closure
2) check every element of each class, if these elements are comparable (has path connected them), compare them. An element can connect to 0 or n element in another class. Throw an exception when they don’t have a connection between them.
for example: i connected to j and h; k and u are in an same equivalence class ; j connected to k
i -> j -> k <-> u
|
v
h
3) if two elements are in the same equivalence class they are equal (0); if they have a path from i to j then i < j (-1), otherwise i > j (1).
4) each equivalence class only appears once and each equivalence class contains at least one element.
Here is a function:
let cmp_classes m c c' =
match c, c' with
| i :: is, j :: js ->
(* when i and j has path *)
if m.(i).(j) = true then compare i j else
(* when i and j don't have path*)
if m.(i).(j) = false then
(* find k in js *)
...
(* check if i and k has path or not, if yes: compare i k; if no: find h in is*)
....
(* find h in is*)
....
(* check if h has path to j or not, if yes: compare h j; if no: check h and k *)
.....
(* check h and k has path or not, if yes: compare h k; if no: there is no path*)
.....
| _ -> assert false
I want you to help me, because I want to be able to write more function trustworthy from the beginning by having a good and clear description. Thank you so much.
I’m not sure I understand your question but I can try to answer anyway.
To reprensent your equivalence classes, you don’t need a list of ints. You can either pick a unique representant (the smaller int of the class for instance) or you can pick any (as you don’t really care, as you have the transitive closure of the relation available anyway);
If your boolean matrix represents the transitive closure of your relation, then to compare two elements, you just have to check the booleans …