【发布时间】:2018-03-11 05:38:51
【问题描述】:
我有以下代码用于可扩展的 AST。我的目标是允许稍后使用 Expr 类添加更多表达式类型,而不是将所有类型都放在一个数据块中。
data Constant o = Constant o deriving (Show)
data Add l r o = Add (l o) (r o) deriving (Show)
class Expr e where
simplify :: (Expr a, Num o) => (e o) -> (a o)
instance Expr Constant where
simplify (Constant a) = Constant a
instance (Expr l, Expr r) => Expr (Add l r) where
simplify (Add l r) = case (simplify l, simplify r) of
(Conatant a, Constant b) -> Constant $ a + b
(sl@_, sr@_) -> Add sl sr
我遇到了这些错误:
math.hs:10:27: error:
• Couldn't match type ‘a’ with ‘Constant’
‘a’ is a rigid type variable bound by
the type signature for:
simplify :: forall (a :: * -> *) o.
(Expr a, Num o) =>
Constant o -> a o
at math.hs:10:3-10
Expected type: a o
Actual type: Constant o
• In the expression: Constant a
In an equation for ‘simplify’: simplify (Constant a) = Constant a
In the instance declaration for ‘Expr Constant’
• Relevant bindings include
simplify :: Constant o -> a o (bound at math.hs:10:3)
math.hs:15:21: error:
• Couldn't match type ‘a’ with ‘Add l0 r0’
‘a’ is a rigid type variable bound by
the type signature for:
simplify :: forall (a :: * -> *) o.
(Expr a, Num o) =>
Add l r o -> a o
at math.hs:13:3-10
Expected type: a o
Actual type: Add l0 r0 o
• In the expression: Add sl sr
In a case alternative: (sl@_, sr@_) -> Add sl sr
In the expression:
case (simplify l, simplify r) of { (sl@_, sr@_) -> Add sl sr }
• Relevant bindings include
sr :: r0 o (bound at math.hs:15:12)
sl :: l0 o (bound at math.hs:15:6)
simplify :: Add l r o -> a o (bound at math.hs:13:3)
我不明白为什么这不起作用。再说一次,我对 Haskell 还是很陌生,因为我在 OOP 领域花了近十年的时间。我希望有人可以让我对此有所了解。
我正在尝试在没有任何 GHC 扩展的情况下执行此操作,因为我想在开始添加更多内容之前了解原版语言。
【问题讨论】:
标签: haskell