[Haskell-cafe] Ambiguous type variable
Jacek Generowicz
jacek.generowicz at cern.ch
Fri Oct 15 19:14:51 EDT 2010
On 2010 Oct 16, at 00:51, Ivan Lazar Miljenovic wrote:
> On 16 October 2010 09:47, Jacek Generowicz
> <jacek.generowicz at cern.ch> wrote:
>> -- Given a definition of view which is essentially a synonym for
>> show:
>>
>> class View a where
>> view :: a -> String
>>
>> instance View Int where
>> view = show
>>
>> -- why does "show 2" compile, while "view 2" gives an
>> -- 'Ambiguous type variable' error
>>
>> fine = view (2::Int)
>> noProblem = show 2
>> ambiguousTypeVariable = view 2
>
> "2" is a generic number. If you don't specify a type, it usually
> defaults to Integer. All Num instances that come in the Prelude have
> Show instances, so no matter which gets picked "show 2" works.
> However, when you say "view 2" ghc/ghci doesn't know that you want 2
> to be an Int (as that's the only type you have an instance for View
> for).
Which implies that defining all instances of Num to be instances of
View should do the trick, and that doesn't seem to work. See below.
On 2010 Oct 16, at 00:51, Christopher Done wrote:
> Don't integral literals default to Integer, of which there is a Show
> instance but no View instance?
Hmm, it doesn't seem to be that simple.
The phenomenology seems to be:
As far as entering "view 2" into ghci is concerned, you need 'instance
View Integer' or 'instance View Double'.
To get "x = view 2" to compile in ghc, having all of Int, Integer,
Float and Double as instances of View is still not enough.
I did all this in an environment where I had not imported any other
Num instances, and ":i Num" in ghci showed only the 4 aforementioned
types as instances.
More information about the Haskell-Cafe
mailing list