I wrote a OCaml program for union find
algorithm. This algorithm I wrote is not optimal and is the simplest version.
I put my OCaml code here because I am not sure whether this code is good enough or not (despite of the algorithm itself), although this code can run without errors.
This is the first time I wrote a complete working thing after I started to learn OCaml, so please help me by reviewing it.
Useful suggestions will help me improving my OCaml skills. Thanks
type union_find = {id_ary : int array; sz_ary : int array};;
let create_union n = {id_ary = Array.init n (fun i -> i);
sz_ary = Array.init n (fun i -> 1)};;
let union u p q =
let rec unionfy id_ary i =
let vp = id_ary.(p) in
let vq = id_ary.(q) in
if i < Array.length id_ary then begin
if i != q && id_ary.(i) = vp then id_ary.(i) <- vq;
unionfy id_ary (i + 1)
end
else print_string "end of union
"
in
unionfy u.id_ary 0;;
let is_connected u p q = u.id_ary.(p) = u.id_ary.(q);;
First of all,
Am I creating the data structure of union
(as in union find
) correctly?
Should I include two arrays inside or is there any better way?
Second,
I am using array
in this code, but array
is mutable
which is not that good for fp
right?
Is there a way to avoid using array?
Finally,
Overall, is this piece of code good enough?
Anything can be improved?
P.S. I am not using OCaml's object oriented bit yet, as I haven't learnt to that part.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…