I'm new to Haskell and currently trying to figure out how to write my own typeclasses. This is what I've got so far:
data Signal = X | O
class Show a where
show :: a -> String
instance Show Signal where
show X = "X"
show O = "O"
And when I try this out I get an error :
Ambiguous occurrence `Show'
It could refer to
either `Prelude.Show',
or `Main.Show
And I can't figure out why that is because I thought the whole point of typeclasses in Haskell was that it made overloading of functions possible? Thanks in advance for your help!
And I can't figure out why that is because I thought the whole point of typeclasses in Haskell was that it made overloading of functions possible?
That is correct, but you here define a new typeclass Show
that is clashing with the one in the Prelude
.
If you define an instance, then it is ambiguous to which Show
typeclass it is referring. To the one defined in the Prelude
(where al lot of types are members of), or the one you defined in your own program.
You thus can define this as:
data Signal = X | O
-- no definition for Show
instance Show Signal where
show X = "X"
show O = "O"
If you want to define your own typeclass, you can work with:
import Prelude hiding (Show)
data Signal = X | O
class Show a where
show :: a -> String
instance Show Signal where
show X = "X"
show O = "O"
but that is probably not a good idea, since all the other types are no member of the new typeclass, only a member of the one defined in the Prelude
.
A typeclass can thus be seen as an interface in languages like Java: your data types can be members of a typeclass if they define an instance that thus defines the implementation of the methods (here show
). But if two interfaces have the same name, that does not mean that these are the same interface.