type class VS struct/functor

Rijk-Jan van Haaften rjchaaft@pop.students.cs.uu.nl
Thu, 24 Jan 2002 00:09:44 +0100


At 13:15 2002-01-22 -0500, Hongwei Xi wrote:
><...>
>In Haskell, I guess that the one implemented later is always chosen.
>Why can't I have two different implementations for an interface?

Actually, I can't think of situations where I would desire this.
Could you please give an example?

>Another problem with Haskell classes is that there is currently
>no way of hiding type information. For instance, suppose that
>I want to implement a module for operations on sets but I do
>not want to reveal what data representation I use for sets. Is
>there a way of doing this in Haskell?
>
>--Hongwei

There is: Use restricted exports. Only export functions on the
datatype, and don't export the datatype itself. For example:

-----------------------
Module Set
         ( emptySet
         , makeSet
         , firstOfSet
         ) where

-- Not exported, only locally visible
data Set a = EmptySet | OneElementSet a

-- Using these functions, everyone can
-- make, change and read Set's
emptySet :: Set a
emptySet = EmptySet

makeSet :: a -> Set a
makeSet x = OneElementSet x

firstOfSet :: Set a -> a
firstOfSet EmptySet             = error "Set.firstOfSet: Empty set"
firstOfSet (OneElementSet x)    = x
-----------------------

Regards,

Rijk-Jan van Haaften