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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With