Haskell中的Monadic TicTacToe出错

时间:2013-11-28 23:39:25

标签: haskell monads

我开始在Haskell中实现TicTacToe:

import Control.Monad.State

data Player = X | O
data Field = Player | I deriving (Eq, Show, Read)

data GameField = G [[Field]]

type GameState = State GameField ()

initGame :: GameState
initGame = do
    put $ G [[I,I,I],[I,I,I],[I,I,I]]

action = do
    initGame

test = execState action $ G [[I,I,I],[I,I,I],[I,I,I]]

当我执行“test”时,我收到以下错误:

No instance for (Show GameField) arising from a use of `print'
Possible fix: add an instance declaration for (Show GameField)
In a stmt of an interactive GHCi command: print it

这个问题的原因是什么,我该如何解决?

2 个答案:

答案 0 :(得分:5)

其实不是太神秘的消息。如果没有Show个实例,请添加一个:

data GameField = G [[Field]] deriving (Show)

答案 1 :(得分:2)

你只是忘了在你的GameField decleration上添加'deriving show'。这可以通过添加它来解决,就像这样

import Control.Monad.State

data Player = X | O
data Field = Player | I deriving (Eq, Show, Read)

data GameField = G [[Field]]
  deriving Show

type GameState = State GameField ()

initGame :: GameState
initGame = do
    put $ G [[I,I,I],[I,I,I],[I,I,I]]

action = do
    initGame

test = execState action $ G [[I,I,I],[I,I,I],[I,I,I]]