Thursday, July 5, 2012

Parametric polymorphism pleases...

Tasty


I still write the occasional bit of OCaml for a project I maintain.  Its a language which I am very happy to write code in, since I get pretty far without too much work.

Here is an interface snippet for a bit of code that translates an equivalence relation (represented as a list of pairs) into a set of equivalence classes (represented as a list of lists of items).

(** UnionFind
  This breaks an equivalence relation into 
  equivalence classes
  *)

val unionfind : ('a * 'a) list -> 'a list list

An example invocation which happens to use int for 'a:

let input1 = [ 1,2;3,4;5,6;7,8;8,3;6,1 ]

let res = unionfind input1

The res evaluates to [[1;2;6;5];[3;4;8;7]].
My really basic implementation of unionfind is embarrassingly sub-optimal (so I won't post it unless somebody asks). But, in my defense, the simple code that I wrote to do this works well enough so far in the context it is used in. Simple things are easier to write correctly anyway.

No comments:

Post a Comment