[Haskell-beginners] understanding type classes and class constraints

Brandon Allbery allbery.b at gmail.com
Mon Nov 18 00:57:27 UTC 2013


On Sun, Nov 17, 2013 at 7:47 PM, Robert Krahn <robert.krahn at gmail.com>wrote:

> instance Tester Integer where
>     test 0 = False
>     test _ = True
>
> For the Maybe instance I want to delegate to the value of Just and add a
> class constraint:
>
> instance (Tester m) => Tester (Maybe m) where
>     test Nothing = False
>     test (Just x) = test x
>
> It compiles nicely and works for Just values
> test (Just 3) -- True
> test (Just 0) -- False
>
> But
> test Nothing
>
> gives me
>     No instance for (Tester a0) arising from a use of `test'
>

Several things are happening here. First is that numbers undergo
defaulting; with nothing else to specify the type of `3` or `0`, they
default to Integer and all is well.

This cannot be said of `Nothing`; it needs to pick an instance, but
`Nothing` doesn't give it anything to work from.

"But I only have an instance for Integer!" Typeclasses work under the "open
world assumption": a typeclass could be added at any time, so it cannot
commit to a given typeclass instance simply because it only happens to know
of one valid instance. In particular, it cannot conclude that `Nothing` is
of type `Maybe Integer` solely because it happens to only be aware of a
`Tester Integer` instance.

(Instances are program global and cannot be hidden, so not making the open
world assumption could easily cause programs to completely change their
meaning with the addition of a single additional instance *anywhere* in
that program, even if not imported to that module.)

-- 
brandon s allbery kf8nh                               sine nomine associates
allbery.b at gmail.com                                  ballbery at sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad        http://sinenomine.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20131117/f931b38b/attachment.html>


More information about the Beginners mailing list