Version française
Home     About     Download     Resources     Contact us    
Browse thread
stl?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Wolfgang Lux <wlux@u...>
Subject: Re: [Caml-list] stl?
Brian Hurt wrote:

> [...]
> Here are two real problems I've hit with type classes, in only a  
> few weeks banging around in Haskell.
>
> For example, you can't have more than one instance of a type class  
> for any given type.  So let's say you want to have a type class for  
> things that can be converted to and from s-expressions, like:
> 	data Sexp =
> 		Atom String
> 		| List [ Sexp ]
>
> 	class Sexpable a where
> 		toSexp :: a -> Sexp
> 		fromSexp :: Sexp -> Maybe a
>
> So then you start throwing out the standard instances, among  
> others, you do one for string:
> 	instance Sexpable String where
> 		toSexp s = Atom s
> 		fromSexp (Atom s) = Just s
> 		fromSexp _ = Nothing
>
> and, a little while later, one for generic lists:
> 	instance Sexpable a => Sexpable [ a ] where
> 		toSexp xs = List $ map toSexp xs
> 		fromSexp (List xs) = mapM fromSexp xs
> 		fromSexp _ = Nothing
>
> Opps!  Now you have conflicting instances for type String- one the  
> explicit implementation, and one via the generic list.  There are  
> kludges to get around this, but they cause their own problems  
> (Brian's first law of programming: kludges multiply).  A common one  
> is to add the function toSexpList and fromSexpList to the  
> fundamental type class, and drop the generic list implementation.

Just to fair to Haskell here, you should not drop the list instance  
altogether, but rather redefine it to use the new methods.

   instance Sexpable a => Sexpable [ a ] where
     toSexp = toSexpList
     fromSexp = fromSexpList

Thus, the purported problem with Map Int ([Int], Foo) is void.

Wolfgang