[Fwd: Re: type class VS struct/functor]

Ahn Ki-yung kyagrd@bawi.org
Sat, 19 Jan 2002 11:59:10 +0900

Hmm ... How do you solve this in Haskell ?

-------- Original Message --------
Subject: Re: type class VS struct/functor
Date: Sat, 19 Jan 2002 01:34:32 GMT
From: neelk@alum.mit.edu (Neelakantan Krishnaswami)
Reply-To: neelk@alum.mit.edu
Organization: ATT Broadband
Newsgroups: comp.lang.functional
References: <3C48C86E.9282BE00@bawi.org>

On Sat, 19 Jan 2002 10:14:22 +0900, =?EUC-KR?B?vsix4r+1?=
> What does ML struct/functor have anything better than type classes ? 
> For the user type classes feels like implicit functor istantiations
> to specific sturucture, and struct/functor seems just bugglling the
> user to do more typing which can be automated by using type classes.

The advantage of functors shows up when you need to have multiple
implementations of a module for a type. For instance, suppose you
want to implement a set, and you write the functors (OCaml below):

  module type EQ =
      type t
      val eq : t -> t -> bool

  module type SET =
      type elt
      type set

      val empty : set
      val add : elt -> set -> set
      val mem : elt -> set -> bool

  module Set(Eq : EQ) : SET with type elt = Eq.t = 
      type elt = Eq.t
      type set = elt list
      let empty = []
      let add elt set = elt :: set
      let rec mem elt set =
	match set with
	|	[] -> false
	|	x :: xs -> if Eq.eq x elt then true else mem elt xs

Now, suppose you want two kinds of sets of string, one of which is
case-sensitive and one of which is not. You can easily do this with
functors like so

  module SensitiveCase =
      type t = string
      let eq s s' = (s = s')

  module InsensitiveCase =
      type t = string
      let eq s s' = (String.lowercase s) = (String.lowercase s')

  module SensitiveSet = Set(SensitiveCase)      
  module InsensitiveSet = Set(InsensitiveCase)

Each of these Set types takes a string, but the membership test is
different. This is an annoying case in Haskell, because you can make a
String a member of the Eq typeclass in only one way.

However, I think it's true that typeclasses are less verbose in the
common case. Personally, I want a language with both typeclasses and
functors, so that I can use either as the problem requires.