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?
PS: 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:
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 have to pick a particular solution type, such as Int.
So how does Show
work? 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.
The reason something like show 3
works in the first place is due to the defaulting rule which picks a particular type when there is an ambiguity involving the Num
class. The reason it doesn't work with your Some
class is that the rule says that all classes involved have to be standard classes (ie, from the Prelude etc.). This latter part of the rule is somewhat silly in opinion.
问题: 3
的类型是Num a => a
,但是ghc需要一个具体的类型才能搜索Some
的实例(可能存在多个Some
实例,这些实例在Num
- 所以哪一个实例选择?)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.