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: Peng Zang <peng.zang@g...>
Subject: Re: [Caml-list] stl?
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


On Wednesday 04 March 2009 11:14:50 am Brian Hurt wrote:
> Yeah.  I think of this as one of the advantages of Functors.
>
> 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.  Except now you can't simply toSexp a value
> of type Map Int ([Int], Foo) despite the fact that Maps, Ints, Foos, and
> tuples all have toSexp defined over them- that list in there says that you
> have to pick things apart by hand, so you can call toSexpList instead of
> toSexp at the right point.

Yeah, I can see the problem with Haskell type classes.  In OCaml though, I 
don't see how this is an issue.  Let's say we are building the class for 
StringObj.  We have a field for the data (type String) and now we implement 
the methods for working on Strings.  When it comes to the sexp methods, 
either implementation can be used.  You can choose.  If the implementation is 
written else where and we want to use inheritance, we can inherit both 
implementations and the last one is the effective one.  It's not a big issue.

Peng
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.7 (GNU/Linux)

iD8DBQFJrq7ufIRcEFL/JewRAi9zAJ96Ur/f79pFWJRaXGXwJMHcU1eTNgCg0rNo
JPEqD48wWiD8XVaafSVwdrc=
=tBvY
-----END PGP SIGNATURE-----