我正在尝试做作业但是我遇到了一个我不理解的语法错误。
data CTree a b =
CNode (CTree a b) b (CTree a b) | -- left, value, right
CLeaf a -- value
deriving (Show, Ord)
-- a)
--
instance (Ord a, Ord b) => Ord (CTree a b) where
--
-- Compares two CNode objects
--
(CNode left1 v1 right1) `compare` (CNode left2 v2 right2) =
-- If the value of the first node is greater than
-- the value of the second node, the result is GT.
if (v1 > v2) then GT
-- If the value of the first node is smaller than
-- the value of the second node, the result is LT
else if (v2 < v1) then LT
-- We must compare the child nodes if the values of
-- boths nodes equal.
else if (v1 == v2) then
if (left1 == left2) then
(right1 `compare` right2)
else
(left1 `compare` left2)
main = do
print "foo"
错误是(在main = do
)行
解析错误(可能是错误的缩进或括号不匹配)
我知道比较函数有一些重载缺失,但语法错误不应该源于这个事实。
答案 0 :(得分:4)
在您的代码中,if (v1 == v2)
有一个then
分支,但缺少else
分支。您应该删除if
,因为您之前检查过v1 < v2
和v1 > v2
,这是没有用的。
答案 1 :(得分:1)
你应该缩进:
if (left1 == left2) then
(right1 `compare` right2)
else
(left1 `compare` left2)
再一层,并为相应的else
提供if (v1 == v2) then
。
然后,您应该从Ord
移除deriving
并添加Eq
。由于您的b
类型为Ord
,因此您只需将程序重写为:
data CTree a b =
CNode (CTree a b) b (CTree a b) |
CLeaf a
deriving (Show, Eq)
instance (Ord a, Ord b) => Ord (CTree a b) where
(CNode _ v1 _) `compare` (CNode _ v2 _) = v1 `compare` v2
main = do
print "foo"
我注意到我已经改变了CTree
instance (Ord a, Ord b) => Ord (CTree a b) where
(CNode left1 v1 right1) `compare` (CNode left2 v2 right2) =
if (v1 == v2) then
if (left1 == left2) then
(right1 `compare` right2)
else
(left1 `compare` left2)
else v1 `compare` v2
函数的含义,因为你的函数永远不会返回compare
,这实际上是预期的值。
但如果你想保持这种行为,你可以这样做:
{{1}}