[Haskell-beginners] Implementing Read

Peter Hall peter.hall at memorphic.com
Sun Sep 11 23:27:53 CEST 2011


Thanks,
Good spot on the order. I'll get to that, but I still didn't have
success with your other suggestion.

readsPrec _ (a:b) = Card{ suit=(toSuit a), rank=(read b) }

The error is:

Card/Card.hs:24:21:
    Couldn't match expected type `[(Card, String)]'
           against inferred type `Card'
    In the expression: Card {suit = (toSuit a), rank = (read 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'


Peter


On Sun, Sep 11, 2011 at 8:05 PM, Daniel Fischer
<daniel.is.fischer at googlemail.com> wrote:
> 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