The ambiguity between the Haskell Num class and my show class

I am trying to declare my own data with the appropriate conversion as a class. My code is as follows:

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 the GHC (7.0.3) is 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 signing (e.g. 3 :: Int) fixes the problem, but it is very inconvenient.
The standard "Show" works fine, and in accordance with the manual, he said exactly the same.

Why does the standard Show work, but my class does not work? Did I miss something?

PS: The explicit "default (Int)" does not allow this.

+4
source share
3 answers

You are correct in overloading. This is a bit complicated. First, you will need to give a type signature to enable numerical overload in your example:

 Ambiguous type variable `a0' in the constraints: (Some a0) arising from a use of `toSome' at A.hs:11:16-21 (Num a0) arising from the literal `3' at A.hs:11:23 

this means, as you noticed, that you need to choose a specific type of solution, for example Int.

So how does Show work? By the magic of extended default rules . Show is special, and GHCi allows you to use some special default rules to help you enter Show to Integer arguments by default.

Your new class is not one of the magic classes that the extended default function knows about, it is so sad that you will need to give type annotations.

+4
source

The reason something like show 3 works in the first place is due to the default rule, which selects a particular type when there is uncertainty involving the Num class. The reason it doesnโ€™t work with your Some class is because the rule says that all participating classes should be standard classes (i.e. From Prelude, etc.). This last part of the rule is a little silly in the eyes.

+1
source

: type 3 is Num a => a , but to search for an instance of Some ghc you need a specific type, (maybe there can be more than one instance of Some that is in Num - so which one to choose?)

0
source

All Articles