Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Haskell typeclasses

Name: Anonymous 2013-07-07 16:04

Hey /prog/. I have the following Haskell program (a simplified example, obviously):

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

class C a

instance C a => Show a


and when I load it in ghci, it complains about overlapping Show instances:

*Main> 1

<interactive>:2:1:
    Ambiguous type variable `a0' in the constraints:
      (Num a0) arising from the literal `1' at <interactive>:2:1
      (Show a0) arising from a use of `print' at <interactive>:2:1
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression: 1
    In an equation for `it': it = 1
*Main> 1 :: Int

<interactive>:3:1:
    Overlapping instances for Show Int
      arising from a use of `print'
    Matching instances:
      instance Show Int -- Defined in `GHC.Show'
      instance C a => Show a -- Defined at tc.hs:5:10
    In a stmt of an interactive GHCi command: print it


What I want to know is, why is it using the Show instance I defined? I haven't defined any instances of C, so the constraints aren't satisfied for Int (or any type) and there should be no ambiguity. Does it not even attempt to check because of the extensions I'm using?

Thanks.

Name: Anonymous 2013-07-08 3:57

You've defined the instance polymorphically for any and all a, that's all it knows. That's the power of parametric polymorphism in Haskell.
Your question is born of vanity. Try writing something useful.

Name: Anonymous 2013-07-08 4:32

Add the OverlappingInstances extension:
{-# LANGUAGE FlexibleInstances, UndecidableInstances, OverlappingInstances #-}

class C a

instance C a => Show a


Testing it:
$ ghci x.hs
GHCi, version 7.6.2: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> 1
1
*Main>

Name: Anonymous 2013-07-08 14:07

>>2
Your question is born of vanity. Try writing something useful.
I was, this is a simplified example so you don't have to look through any more code than necessary. And I don't see what vanity has to do with it.

>>3
Cool, thanks for the help.

Don't change these.
Name: Email:
Entire Thread Thread List