[Haskell-beginners] Idiomatic way to avoid type class instance definitions for Int and Integer separately

Amitava Shee amitava.shee at gmail.com
Tue Mar 15 20:21:40 CET 2011

While reading "Learn You a Haskell for Great Good!" I came across the YesNo
type class

I tried a minimal version as below

module Kind where

class Yesno a where
    yesno :: a -> Bool

instance Yesno Int where
    yesno 0 = False
    yesno _ = True

I was surprised to get an error

*Kind> :load kind.hs
[1 of 1] Compiling Kind             ( kind.hs, interpreted )
Ok, modules loaded: Kind.
*Kind> yesno 10

    Ambiguous type variable `t' in the constraints:
      `Num t' arising from the literal `10' at <interactive>:1:6-7
      `Yesno t' arising from a use of `yesno' at <interactive>:1:0-7
    Probable fix: add a type signature that fixes these type variable(s)

Turns out 10 in this instance is an Integer and I have not defined Yesno
over Integer

Easy fix - just define an instance over Integer

instance Yesno Integer where
    yesno 0 = False
    yesno _ = True

My question - Is there a way to avoid this kind of boilerplate? What is the
idiomatic way?

Thanks & Regards,
Amitava Shee
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110315/bbfce7f9/attachment.htm>

More information about the Beginners mailing list