[Haskell-cafe] Ambiguous type variable
Daniel Fischer
daniel.is.fischer at web.de
Fri Oct 15 19:25:19 EDT 2010
On Saturday 16 October 2010 01:14:51, Jacek Generowicz wrote:
> 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.
http://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-790004.3.4
Defaulting only takes place when all involved classes are defined in the
Prelude or the standard libraries.
Your View class isn't, hence there's no defaulting.
It works in ghci because ghci uses extended default rules (otherwise it
would have to give too many `ambiguous type variable' messages).
>
> 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.
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list