[Haskell-beginners] Re: Classes in Polymorphic Constructors

Brandon S Allbery KF8NH allbery at ece.cmu.edu
Mon Aug 23 13:28:01 EDT 2010


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 8/23/10 12:12 , John Smith wrote:
> On 23/08/2010 18:32, Ertugrul Soeylemez wrote:
>> John Smith<voldermort at hotmail.com>  wrote:
>>
>>> Why can polymorphic data constructors not be instantiated as a class?
>>> (not sure if I used the right terminology there)
>>>
>>> For example,
>>>
>>> a = [1,True]::[Show]
>>> b = "foo":a
>>> c = map show b
>>>
>>> This would obviate the need for wrapper types
>>
>> Your type signature doesn't make sense.  You are confusing type classes
>> with types.  Show is a type class.
> 
> My question was why doesn't the type system allow classes to be used in this
> way. It's the equivalent of a base class or interface in OO.

Typeclasses are not classes, and Haskell values are not objects.  In OO
languages, objects carry around dictionaries with full details of what they
can do.  Haskell values, on the other hand, don't actually carry around
anything; what they can do is specified by the type.  If the type is (Show a
=> [a]), that means the *only* thing you can do with an (a) is to call
(show) on it.

(1) Since this is almost certainly not what you intend, Haskell insists you
acknowledge that by specifying the type as ([forall a. Show a => a]), making
it explicit that the scope of (a) is limited to inside the brackets ---
meaning that, since anything wanting to use it has to go through the
brackets, *all* it knows is that it can invoke (show) on it.

(2) Again, values are not objects --- there is no method dictionary hidden
inside of them.  Typeclass dictionaries are carried *outside* of values, as
hidden arguments to functions that are declared with types that are
typeclass members.  Which is why you can't say (a = [1,True] :: [forall a.
Show a => a]):  there's nowhere to put the dictionary in the value
([1,True]).  This is why a wrapper is required; the wrapper provides a place
for the hidden argument.

Summary:  If you want an OO language, use an OO language.  Haskell isn't one.

There are some outdated examples of OO extensions for Haskell that I don't
think are maintained any more, notably "OOHaskell".  They're not maintained
due to lack of interest.  If you want such a thing, you'll have to modernize
it yourself.

- -- 
brandon s. allbery     [linux,solaris,freebsd,perl]      allbery at kf8nh.com
system administrator  [openafs,heimdal,too many hats]  allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university      KF8NH
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.10 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkxyr6EACgkQIn7hlCsL25XW/QCZAcpQFDxw/ukQlOpPn5zA18tE
vH0AoIh944GcFo1ASFoLxvIHldY9v5DR
=F+gL
-----END PGP SIGNATURE-----


More information about the Beginners mailing list