[Haskell-beginners] Implementing Read
Daniel Fischer
daniel.is.fischer at googlemail.com
Sun Sep 11 21:05:11 CEST 2011
On Sunday 11 September 2011, 20:32:32, Peter Hall wrote:
> instance Show Card where
> show Card { suit = Club, rank = a } = show a ++ "c"
> show Card { suit = Spade, rank = a } = show a ++ "s"
> show Card { suit = Heart, rank = a } = show a ++ "h"
> show Card { suit = Diamond, rank = a } = show a ++ "d"
>
>
> instance Read Card where
> readsPrec (a:b) = Card{ suit=(toSuit a), rank=(read b) }
> where
> toSuit s
>
> | s=='c' = Club
> | s=='s' = Spade
> | s=='d' = Diamond
> | s=='h' = Heart
>
> The error is:
> Card/Card.hs:24:12:
> Couldn't match expected type `Int' against inferred type `[a]'
> In the pattern: a : b
> In the definition of `readsPrec':
> readsPrec (a : b)
> = Card {suit = (toSuit a), rank = (read b)}
> where
> toSuit s | s == 'c' = Club
>
> | s == 's' = Spade
> | s == 'd' = Diamond
> | s == 'h' = Heart
>
> In the instance declaration for `Read Card'
>
>
>
> Where am I going wrong?
readsPrec takes a precedence level as first argument (to determine whether
parentheses are necessary).
If you want to ignore that for the moment, changing your definition to
readsprec _ (a:b) = ...
should work.
However, you show cards in the order rank, suit, but you read them suit,
rank. It would be better to be consistent with read and show (so that
read (show x) == x).
More information about the Beginners
mailing list