Why am I getting an ambiguous occurrence error when I define an instance?

I have a type Foo

and want to make it an instance Show

, so I can use it in GHCi:

data Foo = Foo

instance Show Foo where
show Foo = "Foo"

      

However, when I try to use it, I get an ambiguous error:

ghci> show Foo
<interactive>:4:1:
    Ambiguous occurrence `show'
    It could refer to either `Main.show', defined at Foo.hs:4:1
                          or `Prelude.show',
                             imported from `Prelude' at Foo.hs:1:1
                             (and originally defined in `GHC.Show')

      

Why? I just defined a function that belongs to the styles class, right?

+3


source to share


1 answer


TL; DR: The anchoring indents of your instances.


Turn on warnings and you will notice that you haven't implemented an instance operation show

, but instead a new function with the same name:

Foo.hs:3:10: Warning:
    No explicit implementation for
      either `showsPrec' or `Prelude.show'
    In the instance declaration for `Show Foo'

      

So now there are two show

s. Main.show

(the one you randomly identified) and Prelude.show

(the one you wanted to use).



We can verify that by looking at their types (although we need to fully qualify their names):

ghci> :t Main.show
Main.show :: Foo -> [Char]
ghci> :t Prelude.show
Prelude.show :: Show a => a -> String

      

This is because your anchors where

need to be indented, just like you would indent them from a normal function. Even one space is enough:

instance Show Foo where
 show Foo = "Foo"

      

Remember that Haskell uses spaces to separate blocks. Just ask yourself: when will it stop where

?

+5


source







All Articles