Search code examples
haskellpolymorphismocamltypeclass

What's the closest thing to Haskell's typeclasses in OCaml?


What are some ways that I can accomplish what Haskell's typeclasses do in OCaml? Basically, I want to write a polymorphic function without writing too much code. The typical way to do polymorphism is to supply an additional argument telling the function is what type it is currently working on. For example, let's say I want to sort a list of ints, I have to pass an additional comparator to the function.

type comparison = Lesser | Equal | Greater

my_sort : (a' -> a' -> comparison) -> 'a list -> 'a list

Is there anyway to tell OCaml that my type is comparable without writing a comparator function for every type that I want to sort? Which means that my sorting function would look just like this:

my_sort : 'a list -> 'a list

Solution

  • It really depends what you want to achieve.

    If you are happy with the OCaml polymorphic comparison function (which will not work on cyclic and functional values), you can simply write:

    let my_sort l = List.sort Pervasives.compare l
    

    The more generic way to mimic type classes is to use functors:

    module type COMPARABLE = sig
      type t
      val compare: t -> t -> int
    end
    
    module MySort (C: COMPARABLE) = struct
      let sort l = List.sort C.compare l
    end
    
    (* You can now use instantiate the functor *)
    module IntAscending = struct
      type t = int
      let compare = (-)
    end
    module IntDescending = struct
      type t = int
      let compare x y = y - x (* Reverse order *)
    end
    
    module SortAsc = MySort(IntAscending)
    module SortDesc = MySort(IntDescending)