Reputation: 1403
I try, for training, create data structure same as Data.Tree:
data MyTree a = Tree a [MyTree a]
But I have a trouble when I try to create show instance for this data structure:
instance Show (MyTree a) where
show (Tree a [v]) = show a -- Only first element
I get an error
No instance for (Show a)
arising from a use of `show'
It is some strange for me. As I can glance function show is able to work with any types.
And the second question: In the standart library used deriving method, but there are some strange defenitions:
instance Eq a => Eq (Tree a)
instance Read a => Read (Tree a)
instance Show a => Show (Tree a)
instance Data a => Data (Tree a)
What does these means?
Upvotes: 1
Views: 118
Reputation: 8136
Show
can be derived for any type, but if you want to use the derived version, you have to let the compiler know.
In order for your definition show (Tree a [v]) = show a
to work, a
must be an instance of Show
. It could be a derived instance, or a custom instance. So we just need to tell the compiler that a
is an instance of Show
, like this.
instance (Show a) => Show (MyTree a) where
show (Tree a [v]) = show a -- Only first element
A declaration such as instance Eq a => Eq (Tree a)
says "As long as a
is an instance of Eq
, so is Tree a
.
Upvotes: 5