[Haskell-beginners] Implementing Read
Peter Hall
peter.hall at memorphic.com
Sun Sep 11 20:32:32 CEST 2011
I'm having some trouble defining an implementation for "Read". I know
I could model a card more simply as an unconstrained tuplet, but I'm
trying to learn new things about haskell as I go.
module Card.Card (
Suit(..)
,Card(..)
) where
data Suit = Club | Spade | Diamond | Heart
deriving (Eq, Ord, Show, Read, Bounded, Enum)
data Card = Card { suit :: Suit
, rank :: Int
}
deriving (Ord, Bounded, Eq)
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?
Thanks,
Peter
More information about the Beginners
mailing list