functional programming - Simple non-optimal unionfind in OCaml -



functional programming - Simple non-optimal unionfind in OCaml -

i wrote ocaml programme union find algorithm. algorithm wrote not optimal , simplest version.

i set ocaml code here because not sure whether code plenty or not (despite of algorithm itself), although code can run without errors.

this first time wrote finish working thing after started larn ocaml, please help me reviewing it.

useful suggestions help me improving ocaml skills. thanks

type union_find = {id_ary : int array; sz_ary : int array};; allow create_union n = {id_ary = array.init n (fun -> i); sz_ary = array.init n (fun -> 1)};; allow union u p q = allow rec unionfy id_ary = allow vp = id_ary.(p) in allow vq = id_ary.(q) in if < array.length id_ary begin if != q && id_ary.(i) = vp id_ary.(i) <- vq; unionfy id_ary (i + 1) end else print_string "end of union\n" in unionfy u.id_ary 0;; allow is_connected u p q = u.id_ary.(p) = u.id_ary.(q);;

first of all,

am creating info construction of union (as in union find) correctly?

should include 2 arrays within or there improve way?

second,

i using array in code, array mutable not fp right?

is there way avoid using array?

finally,

overall, piece of code enough?

anything can improved?

p.s. not using ocaml's object oriented bit yet, haven't learnt part.

a few stylistic points:

not sure why unionfy takes id_ary parameter since keeps constant throughout

don't utilize array.init constant function. utilize array.make.

print_string "...\n" equivalent print_endline "..."

the next definition can cleaned punning let union u p q = to: let union {id_ary; _} p q there no extraneous references u.

same punning trick let is_connected u p q = u.id_ary.(p) = u.id_ary.(q);;

this might personal selection rid of:

let vp = id_ary.(p) in allow vq = id_ary.(q) in

or @ to the lowest degree shove them above recursive definition it's clear constant.

edit: corrected version

let union {id_ary;_} p q = allow (vp, vq) = (id_ary.(p), id_ary.(q)) in allow rec unionfy = if < array.length id_ary begin if != q && id_ary.(i) = vp id_ary.(i) <- vq; unionfy (i + 1) end else print_endline "end of union" in unionfy 0;;

functional-programming ocaml

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

Hibernate criteria by a list of natural ids -

ios - Lagging ScrollView with UIWebview inside -