[Haskell-beginners] Idiomatic way to avoid type class instance definitions for Int and Integer separately
aditya siram
aditya.siram at gmail.com
Tue Mar 15 20:28:38 CET 2011
Untested, but you might try:
instance (Num t) => YesNo t where ....
-deech
On Tue, Mar 15, 2011 at 2:21 PM, Amitava Shee <amitava.shee at gmail.com> wrote:
> 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
>
> <interactive>:1:6:
> 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
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
More information about the Beginners
mailing list