3

I have a type Foo and want to make it an instance of Show, so that 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 occurrence 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 the function that belongs to a typeclass, didn't I?

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • Note: this question is, just [like my other one](https://stackoverflow.com/questions/35855170/why-shouldnt-i-mix-tabs-and-spaces), intended to be a minimal generic variant of one of the more frequently asked Haskell questions. – Zeta May 05 '17 at 12:15

1 Answers1

6

TL;DR: Indent your instance bindings.


Enable warnings and you will notice that you didn't implement the 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'

Therefore there are now two shows. Main.show (the one you've just accidentally defined) and Prelude.show (the one by the class you've 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

That's because your where bindings need to be indented, just like you would indent them in a usual function. Even a single space is enough:

instance Show Foo where
 show Foo = "Foo"

Remember, Haskell uses whitespace to delimit blocks. Just ask yourself: when would the where stop otherwise?

Zeta
  • 103,620
  • 13
  • 194
  • 236