Haskell 如何检查二叉树是否具有heap属性?
给定一个二叉树,我想检查它是否具有heap属性,例如,如果B是a的子节点,那么key(a)>=key(B):Haskell 如何检查二叉树是否具有heap属性?,haskell,Haskell,给定一个二叉树,我想检查它是否具有heap属性,例如,如果B是a的子节点,那么key(a)>=key(B): 数据树a=Leaf |节点a(树a)(树a) 我已开始履行以下职责: isHeap::树a->Bool isHeap Leaf=True isHeap(节点a左-右)=如果(节点a)>=isHeap(左)和&(节点a)>=isHeap(右),则为True,否则为False 这是错误的,因为GHCI指出它无法将预期的类型Tree a->Tree a->Tree a与实际类型Bool匹配 我
数据树a=Leaf |节点a(树a)(树a)
我已开始履行以下职责:
isHeap::树a->Bool
isHeap Leaf=True
isHeap(节点a左-右)=如果(节点a)>=isHeap(左)和&(节点a)>=isHeap(右),则为True,否则为False
这是错误的,因为GHCI指出它无法将预期的类型Tree a->Tree a->Tree a与实际类型Bool匹配
我知道我做错了,但我认为这是正确的。有什么想法吗?你有一些问题。
首先,要使用=
您需要添加Ord
约束,因此ishap
的类型应该是
isHeap :: Ord a => Tree a -> Bool
其次,除了知道子节点是否满足heap属性外,还需要子节点的值。您可以在子节点类型上进行匹配,例如
isHeap :: Ord a => Tree a -> Bool
isHeap Leaf = True
isHeap (Node a Leaf Leaf) = True
isHeap (Node a c1@(Node b _ _) Leaf) = ...
isHeap (Node a Leaf c2@(Node b _ _)) = ...
isHeap (Node a c1@(Node b _ _) c2@(Node c _ _)) = ...
在最后一个模式中,b
和c
是子节点的值,您需要将其与父节点(a
)的值进行比较,而c1
和c2
是节点本身
为了回答有关错误的问题,节点
构造函数是
Node :: a -> Tree a -> Tree a -> Tree a
因此表达式(节点a)
是类型树a->树a->树a
的函数。当你有
if(节点a)>=isHeap(左)
由于
isHeap left
具有类型Bool
,编译器还希望>=
的左侧具有相同的类型。但是,编写该子句时遇到问题的原因是您没有子节点的值与父节点的值进行比较。旁注:如果您发现自己编写了If-Condition-then-else-False
或If-Condition-then-False-else-True
,您可以只编写条件
或非条件
。