I have a installed module with data type Card. I make it instance of class Show but something go wrong in the ghci:
module Poker where
data Card = Card Int
...
instance Show Card where
show card = ...
...
I open the ghci and type:
>:m + Poker
>Card 0
..
..
..
(Nothing) => I stop the execution
>Poker.show (Card 0)
> "Ace of Hearts"
It seem that my data type is not an instance of the class Show, why?
Thanks all! It works! 🙂
Indentation matters. The body of an instance declaration needs to be indented, otherwise it interprets your definition of
showas just another top-level function, which is whyPoker.showworks.The general indentation rule in Haskell is that if two consecutive lines are indented the same, they are two distinct definitions, whereas if a line is more indented than the one before it, it is considered to be part of the preceding definition or expression, which is what you want in this case.
The reason why this causes an infinite loop, is that since you didn’t provide an implementation of
showin the type class, it uses the default implementation which indirectly callsshowsPrec. Since you didn’t provide that one either, it uses the default implementation which callsshow. Thus, you get an infinite loop. Several type classes have default implementations implemented in terms of each other like that, so that you only have to implement a subset of them.