0
votes

I'm making a simple Tic-Tac-Toe game to learn Haskell. Each cell in the board has either a player value (X or O) or a positional value if the square is empty (letters A-I, such that:

A|B|C
D|E|F
G|H|I

)

To start, I've created a simple function that takes an empty board (which looks like the one above) and a String (a letter "A" through "I"), and returns a board where the letter entered is replaced with an "X". So if I were to call newBoard blankBoard "C", I would expect this to return:

A|B|X
D|E|F
G|H|I

If I want to keep the Square data type as it is, how could I make this code work:

data Square = A | B | C | D | E | F | G | H | I | X | O deriving (Read)
instance Show Square where
  show A = "A"
  show B = "B"
  show C = "C"
  show D = "D"
  show E = "E"
  show F = "F"
  show G = "G"
  show H = "H"
  show I = "I"
type Board = [[Square]]

blankBoard :: Board
blankBoard = [[A,B,C],[D,E,F],[G,H,I]]

newBoard :: Board -> String -> Board
newBoard board letter = [[ if show sq == letter then X else sq | sq <- row ]| row <- board]

I'm getting this error, and not sure why:

[[*** Exception: myfunctions.hs:(386,3)-(394,14): Non-exhaustive patterns in function show
1
You are trying to use show on an X or an O, which is something that you haven't defined. Is there a reason that you don't just use deriving Show for your Square?JHobern
That did the trick, thanks! I didn't realize that X was being shown.Mark Karavan
Enabling warnings would have found this bug at compile time.chi
@JHobern, can you make your comment an answer, so OP can accept? Also, OP, why are you using == on String, not on Square, simply deriving Eq?Tobi Nary

1 Answers

1
votes

The error Non-exhaustive patterns in function means that you have tried to use a function with an argument for which it wasn't defined. In this case, you have tried to use show on either an X or an O, whereas you have only defined it for A through I.

You could fix this by adding:

show X = "X"
show O = "O"

However, since your show function doesn't do anything special at all, you would be better off just using deriving Show, and letting Haskell create the function for you.