实例读取 Haskell

Instance read Haskell

我需要实现数据类型的读取实例

data GameAction = GameAction (Int, Int) deriving (Eq)

我做到了

instance Read GameAction where
  readProc (x:xs:_) = setGA (read x) (read xs)

但我收到错误

`readProc' is not a (visible) method of class `Read'

有什么想法吗??

首先,下次请尝试在您的问题中包含更多信息和上下文,因为这很有帮助。

其次,您的问题似乎只是一个拼写错误:readProcRead 类型类中的实际 readPrec 方法。

第三,实现Read在这里不是必需的,因为它可以很容易地导出:

data GameAction = GameAction (Int, Int) deriving (Show,Eq,Read)

在 ghci 中:

ghci> let x = GameAction (5,6)
ghci> (read . show) x == id x
True

好了。

但更重要的是,您为什么要尝试手动实现 Read 实例? ShowRead 用于 encoding/decoding 数据类型和来自 String,这应该只用于调试目的。如果您想要比自动派生的 Read 实例提供的更专业的东西,您可能正在寻找比 Read 应该用于的东西更多的东西。如果要将 UTF-8 字符串解析为数据类型,请查看将 text 库与 attoparsec 库结合使用。

谢谢大家。

我可以按照以下方式解决我的问题

instance Read GameAction where
readsPrec _ (x:y:rest) = let board = read [x] :: Int;
                       cel = read [y] :: Int;
                       in
                       if all isDigit [x,y] then
                        [(setGA board cel, rest)]
                       else []
readsPrec _ _ = []