[Haskell-cafe] confusion about 'instance'....
jonathanccast at fastmail.fm
Thu Jan 10 23:52:10 EST 2008
On 10 Jan 2008, at 6:04 AM, Nicholls, Mark wrote:
>> -----Original Message-----
>> From: Bulat Ziganshin [mailto:bulat.ziganshin at gmail.com]
>> Sent: 10 January 2008 13:36
>> To: Nicholls, Mark
>> Cc: Luke Palmer; haskell-cafe at haskell.org
>> Subject: Re: [Haskell-cafe] confusion about 'instance'....
>> Hello Mark,
>> Thursday, January 10, 2008, 4:25:20 PM, you wrote:
>> "instance Num a =>> A a"
>>> Mean the same thing as
>>> "instance A (forall a.Num a=>a)"
>> programmers going from OOP world always forget that classes in
>> doesn't the same as classes in C++. *implementation* of this instance
>> require to pass dictionary of Num class along with type. now imagine
>> the following code:
> My confusion is not between OO classes and Haskell classes, but
> are the members of a Haskell type class...I'd naively believed them to
> be types (like it says on the packet!)...but now I'm not so sure.
A type class *is* a set of types. But, in Haskell, types like
(forall a. Num a => a) aren't quite first-class feeling. A typical
example of an expression of this type might be (3 + 5), but if I say
x :: Double
x = 3 + 5
the compiler won't complain.
Furthermore, if the compiler sees
instance A Double where
somewhere in the code, when it sees foo (3 + 5), for some method foo
of the class, it may decide to take (3 + 5) :: Double, not (3 + 5) ::
forall a. Num a => a. In that case, you'll get the wrong methods
class A a where
foo :: a -> String
instance A Double where
foo x = "Double"
instance A (forall a. Num a => a) where
foo x = "number"
If the compiler sees the first instance but not the second, then it
will think that foo (3 + 5) = "Double". Adding the second will give
foo (3 + 5) = "number". Haskell 98's rules for type classes are
chosen so that legal code never changes its meaning when you add an
instance (well, this is a bad example --- but the general point is
sound). GHC relaxes these rules in quite a few cases, but in this
one it's easy enough (in GHC) to get a type isomorphic to forall a.
Num a => a that can be an instance of a type class that GHC hasn't
bothered relaxing this particular rule. (And paying the subsequent
cost in confusion when working code bitrots because somebody added an
More information about the Haskell-Cafe