I'm relatively new to Haskell. Here is what i want to do:
I want parse strings to chesspieces. my code is pretty straightforward so i hope it will explain itself:
data ChessPiece = King | ... etc
data DraughtPiece = DKing | ... etc
data Player = Black | White deriving (Show, Eq)
data Piece a = Piece (a, Player)
So a Piece can be of either 2 games, of either 2 players. I want a string "k" or "K" to respectively parse to a Black or White King, so I made this:
class Parse a where
parse :: String -> a
instance Parse ChessPiece where
parse a = case a of
"k" -> King
Everything fine so far.. i can call > parse "k" :: ChessPiece. this works!
instance Parse a => Parse (Piece a) where
parse x | isLowercase x = Piece (parse x, White)
| otherwise = Piece (parse $ lowercase x, Black)
This has to work for either piece. The rule for uppercase and lowercase goes for DraughtPiece and for ChessPiece. How do i tell Haskell to parse the x to the correct type (a). Leaving out the cast for parse x gives me non-exhaustive pattern error, changing it to parse x :: a gives me 'could not deduce (Parse a1) from a use of 'parse' from the context (Parse a)'
How do i tell Haskell to parse "K" :: Piece ChessPiece to (parse "k" :: ChessPiece, Black) to (King, Black)?
main = print $ (parse "K" :: Piece ChessPiece)printedPiece (King,Black)andmain = print $ (parse "K" :: Piece DraughtPiece)printedPiece (DKing,Black). Your non-exhaustive pattern error might be that you typed "P" before defining the pawn or something. I did secretly add a Queen piece and a couple more show instances, but that wouldn't have fixed it.isLowercasewithall isLowerand replacedlowercasewithmap toLower. Is it possible yourlowercasefunction is broken, so the ChessPiece instance of Parse never gets a "k"? Anyway, can you paste the full text of your non-exhaustive pattern error please?