I’m trying to declare my own data with appropriate conversion as class. My code looks like this:
data SomeData = SInteger Integer | SElse deriving Show
class Some a where
toSome :: a -> SomeData
instance Some Int where toSome = SInteger . toInteger
main :: IO ()
main = print $ toSome 3
But GHC (7.0.3) becomes angry and says:
Ambiguous type variable `a0' in the constraints:
(Some a0) arising from a use of `toSome'
at minimal_broken.hs:11:16-21
(Num a0) arising from the literal `3' at minimal_broken.hs:11:23
Probable fix: add a type signature that fixes these type variable(s)
Explicit type signature (like 3::Int) fixes the issue, but it’s very inconvenient.
Standard “Show” works just fine, and according to the manual it’s declared exactly the same way.
Why standard Show works, but my class doesn’t? Did I miss something?
P.S.: Explicit “default (Int)” does not resolve this.
You’re right about the overloading. It’s a little tricky. Firstly, you will have to give a type signature to resolve the numeric overloading in your example:
this means, as you noticed, that you have to pick a particular solution type, such as Int.
So how does
Showwork? By the magic of extended defaulting rules. Show is special, and GHCi enables some special defaulting rules to help “default” the type in arguments of Show to Integer.Your new class isn’t one of the magic classes that the extended defaulting feature knows about, so sadly, you will need to give type annotations.