我正在为自己的语言编写解释器,并且我有一个具有这种类型的抽象语法树:
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
可修复它。