Haskell多态树和

sai*_*imn 10 polymorphism tree haskell functional-programming sum

我编写了以下用于处理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)
Run Code Online (Sandbox Code Playgroud)

现在我遇到了问题,代码无法编译:

...\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>
Run Code Online (Sandbox Code Playgroud)

你知道treeSum有什么问题吗?我认为它与ITree的多态类型有关,但我不知道如何解决这个问题.我是否必须指定类型t必须是可以计数/枚举的类型?可能有这种类型类的类实例?

在此先感谢您的帮助!

西蒙

jto*_*bin 11

编译器无法验证结果是否为Int.就目前而言,您可以treeSum使用ITree Integer参数调用(并且操作不会生成Int).

尝试将签名更改为treeSum :: Integral t => ITree t -> t.

  • `treeSum :: Num t => ITree t - > t`会更好:它只使用`fromInteger`和`(+)`. (4认同)
  • @saimn这是一个约束,说`t`必须是一个实现`Integral`类型类的类型. (2认同)