我编写了以下代码,用于在 Haskell 中处理多态二叉树,为下周的函数式编程考试做准备:
data ITree t = Leaf | Node t (ITree t) (ITree t)
deriving (Eq, Ord, Show)
treeSum :: ITree t -> Int
treeSum Leaf = 0
treeSum (Node n t1 t2) = n + (treeSum t1) + (treeSum t2)
现在我遇到了问题,代码无法编译:
...\tree.hs:8:26:
Couldn't match type `t' with `Int'
`t' is a rigid type variable bound by
the type signature for treeSum :: ITree t -> Int
at ...\tree.hs:7:1
In the first argument of `(+)', namely `n'
In the first argument of `(+)', namely `n + (treeSum t1)'
In the expression: n + (treeSum t1) + (treeSum t2)
Failed, modules loaded: none.
Prelude>
你知道treeSum有什么问题吗?我认为这与ITree的多态类型有关,但我不知道如何解决这个问题。我是否必须指定类型 t 必须是可以计数/枚举的类型?可能带有这种类型类的类实例?
在此先感谢您的帮助!
西蒙