我有一个枚举数据类型,看起来像这样:
data MathExpr a = X
| Coef a
| Sum (MathExpr a) (MathExpr a)
| Prod (MathExpr a) (MathExpr a)
| Quot (MathExpr a) (MathExpr a)
| Exp (MathExpr a)
| Log (MathExpr a)
deriving (Eq,Show,Read)
我正在尝试将 String 转换为这种类型。我想使用前奏中可用的读取功能。为此,我创建了另一个函数:
readMathExpr :: String -> MathExpr a
readMathExpr = read
这在编译时给我一个错误,说没有因使用“read”而产生的 (Read a) 实例。如果有人能指出我正确的方向或链接与阅读功能有关的有用教程,我将不胜感激。谢谢 !
问题只是您提出的类型签名太笼统了。的派生实例Read
的MathExpr a
时候就已经存在的实例只能Read
为a
。也就是说,如果您要自己写出实例,它将开始:
instance (Read a) => Read (MathExpr a) where ...
我不认为在实践中您会希望读取本身不是 实例的类型MathExpr a
的类型值,因此修复方法只是将必要的类型类约束添加到签名中:a
Read
readMathExpr :: (Read a) => String -> MathExpr a
readMathExpr = read
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句