Loading ...
Sorry, an error occurred while loading the content.

Re: "ocaml_beginners"::[] Haskell Type Classes In OCaml

Expand Messages
  • Brian Hurt
    ... As a general rule, any where you d use type classes in Haskell, the right solution in Ocaml is to use modules & functors (as a side note, the term
    Message 1 of 7 , Mar 1, 2013
    • 0 Attachment
      On Wed, Feb 20, 2013 at 12:59 AM, Jason Yeo <jasonyeo88@...> wrote:

      > Hi,
      >
      > I am trying to achieve some form of polymorphism to print my data
      > structures (ints, floats, List of ints, List of floats or List of
      > ADTs).
      >
      > Is there a way to do it just like in Haskell? Maybe using type classes?
      >
      > For example, I just have to use a function to print both ints and floats.
      >
      > my_print : 'a -> String
      >
      > I understand that they are already papers written about using modules
      > or functors to emulate type classes but the programmer is required to
      > specify what type the function is working on by passing in an extra
      > parameter. This seems kinda cumbersome to me. Is there anyway to do
      > this cleanly like in Haskell?
      >
      > Thanks!
      > Jason
      >
      >
      As a general rule, any where you'd use type classes in Haskell, the right
      solution in Ocaml is to use modules & functors (as a side note, the term
      "functor" means something completely different in Ocaml than in Haskell).

      So you could implement this as:
      module type Printable = sig
      type t
      val my_print : t -> string
      end

      module PrintableList(Printable P) = struct
      type t = P.t list
      let my_print lst = ...
      end

      And so on. This is one of the situations where modules & ocaml functors
      are a little bit clunky compared to type classes, but there are other cases
      where the converse is true.

      Brian


      [Non-text portions of this message have been removed]
    Your message has been successfully submitted and would be delivered to recipients shortly.