我正在为自己的语言编写一个解释器,我有一个抽象语法树,它有这种类型:
data Expression =
PInt Int
| PFloat Double
| PString String
| PChar Char
| PBool Bool
| Var String
| Unbound String String
| Unary String Expression
| Binary String Expression Expression
| Call Expression [Expression]
| Lambda Expression
| Assign String Expression Expression
| Conditional Expression Expression Expression
deriving Eq
我正在尝试为我的班级编写一个Num实例,以便我可以使用现有的机器进行数值运算。这就是我写的:
instance Num Expression where
PInt a + PInt b = PInt $ a + b
PInt a + PFloat b = PFloat $ a + b
PFloat a + PInt b = PFloat $ a + b
PFloat a + PFloat b = PFloat $ a + b
_ + _ = undefined
PInt a - PInt b = PInt $ a - b
PInt a - PFloat b = PFloat $ a - b
PFloat a - PInt b = PFloat $ a - b
PFloat a - PFloat b = PFloat $ a - b
_ - _ = undefined
PInt a * PInt b = PInt $ a * b
PInt a * PFloat b = PFloat $ a * b
PFloat a * PInt b = PFloat $ a * b
PFloat a * PFloat b = PFloat $ a * b
_ * _ = undefined
negate (PInt a) = PInt (-a)
negate (PFloat a) = PFloat (-a)
negate _ = undefined
abs (PInt a) = PInt $ abs a
abs (PFloat a) = PFloat $ abs a
abs _ = undefined
signum (PInt a) = PInt $ signum a
signum (PFloat a) = PFloat $ signum a
signum _ = undefined
fromInteger i = (PInt $ fromInteger i)
这给了我特别在我合并整数和浮点数的地方的错误。
Prelude> :load AST.hs
[1 of 1] Compiling AST ( AST.hs, interpreted )
AST.hs:38:36:
Couldn't match expected type `Double' with actual type `Int'
In the first argument of `(+)', namely `a'
In the first argument of `PFloat', namely `(a + b)'
In the expression: PFloat (a + b)
AST.hs:39:37:
Couldn't match expected type `Double' with actual type `Int'
In the second argument of `(+)', namely `b'
In the second argument of `($)', namely `a + b'
In the expression: PFloat $ a + b
AST.hs:43:33:
Couldn't match expected type `Double' with actual type `Int'
In the first argument of `(-)', namely `a'
In the second argument of `($)', namely `a - b'
In the expression: PFloat $ a - b
AST.hs:44:37:
Couldn't match expected type `Double' with actual type `Int'
In the second argument of `(-)', namely `b'
In the second argument of `($)', namely `a - b'
In the expression: PFloat $ a - b
AST.hs:48:33:
Couldn't match expected type `Double' with actual type `Int'
In the first argument of `(*)', namely `a'
In the second argument of `($)', namely `a * b'
In the expression: PFloat $ a * b
AST.hs:49:37:
Couldn't match expected type `Double' with actual type `Int'
In the second argument of `(*)', namely `b'
In the second argument of `($)', namely `a * b'
In the expression: PFloat $ a * b
Failed, modules loaded: none.
这对我来说没有意义,因为Haskell中Int + Double的类型是Double,所以a + b应该解析为Double,因为PFloat的构造函数需要Double,没问题。 ..为什么不是这样?
已解决:在fromIntegral
类型的变量前面使用Int
修复它。
答案 0 :(得分:3)
Num类型类中的数学运算符期望它们的两个参数具有相同的类型,因此您必须先使用fromIntegral
将Int转换为Double,然后才能将它们添加到一起。
例如,替换此
PInt a + PFloat b = PFloat $ a + b
用这个
PInt a + PFloat b = PFloat $ fromIntegral a + b