Re: "ocaml_beginners":: Haskell Type Classes In OCaml
- On Wed, Feb 20, 2013 at 12:59 AM, Jason Yeo <jasonyeo88@...> wrote:
> Hi,As a general rule, any where you'd use type classes in Haskell, the right
> 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
> 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?
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
val my_print : t -> string
module PrintableList(Printable P) = struct
type t = P.t list
let my_print lst = ...
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.
[Non-text portions of this message have been removed]