【发布时间】:2017-02-05 04:52:03
【问题描述】:
我有一棵非二叉树:
data MultTree b = DataNode b | IndexNode Int Int [MultTree b] deriving (Show)
注意:DataNode's 被视为树叶,IndexNode's 被视为树枝。
现在我尝试在IndexNode 中实现,较小的Int 值设置为子树的DataNode 的最小值,而较大的Int 值设置为DataNode 的最大值子树。
对于没有子树的IndexNode's,较小的Int 值设置为minBound::Int,较大的值设置为maxBound::Int
这是我目前的功能:
dataInterval:: (Ord a) => MultTree a -> MultTree a
dataInterval (DataNode x) = (DataNode x)
dataInterval(IndexNode x y [])
| x > y = (IndexNode (maxBound :: Int) (minBound :: Int) [])
| x < y = (IndexNode (minBound :: Int) (maxBound :: Int) [])
| x == y = (IndexNode x y [])
datenInterval (IndexNode x y subtrees)
| x > y = (IndexNode (maxValue subtrees) (minValue subtrees) (map (dataInterval subtrees)))
| x < y = (IndexNode (minValue subtrees) (maxValue subtrees) (map (dataInterval subtrees)))
| x == y = (IndexNode x y (map (dataInterval subtrees)))
必须递归调用函数dataInterval。
现在我不知道该怎么做,因为dataInterval 需要一棵树,但不知何故我必须调用完整的列表。 dataInterval 不允许这样做。
问题:如何使用列表中的子树递归调用dataInterval?那么subtrees列表的每一棵树都会被调用?
我认为它可能是一些类似地图的功能,但返回的是子树而不是列表。
目前错误消息如下所示:
无法匹配预期类型 MultTree a2 具有实际类型 [MultTree a] * 在 datenIntervalle 的第一个参数中,即子树 在map的第一个参数中,即(datenIntervalle subtrees) 在 IndexNode 的第三个参数中,即 (地图(datenIntervalle 子树))
示例树和完整代码:
t2 :: MultTree Int
t2 = IndexNode 3 42 [IndexNode 7 8 [DataNode 3, DataNode 5, DataNode 7, DataNode 9], DataNode 6, IndexNode 10 23 [DataNode 99, DataNode 78, DataNode 24]]
dataList:: MultTree a -> [a]
dataList(DataNode x) = [x]
dataList(IndexNode _ _ subtress) = concat' (map dataList subtress)
maxValue :: (Ord a) => MultTree a -> a
maxValue tree = maximum (dataList tree)
minValue :: (Ord a) => MultTree a -> a
minValue tree = minimum (dataList tree)
dataInterval:: (Ord a) => MultTree a -> MultTree a
dataInterval(DataNode x) = (DataNode x)
dataInterval(IndexNode x y [])
| x > y = (IndexNode (maxBound :: Int) (minBound :: Int) [])
| x < y = (IndexNode (minBound :: Int) (maxBound :: Int) [])
| x == y = (IndexNode x y [])
dataInterval(IndexNode x y subtrees)
| x > y = (IndexNode (maxValue subtrees) (minValue subtrees) (map (dataInterval subtrees)))
| x < y = (IndexNode (minValue subtrees) (maxValue subtrees) (map (dataInterval subtrees)))
| x == y = (IndexNode x y (map (dataInterval subtrees)))
【问题讨论】:
-
您的
dataIntervalsubtreesminValue和maxValue未定义,afaik? -
@WillemVanOnsem :对不起,我已经更新了我的问题。
-
如果你说:“现在我尝试在 IndexNode 中实现,较小的 Int 值设置为子树的最小 DataNode,而较大的 Int 值设置为子树的最大 DataNode。”由于 IndexNode Int Int ...,不需要类型 b 是 Int 吗?此外,为了澄清,DataNodes 总是树的叶子吗?
-
@SlavenGlumac:在我的解释中是“价值”缺失。我已经更新了我的帖子。因此 IndexNode 的较小 int 设置为您可以在子树的叶子中找到的最小值。 IndexNode 的较大 Int 设置为您可以在子树的叶子中找到的最大值。是的,DataNode 总是叶子。
-
你想要
map dataInterval subtrees而不是map (dataInterval subtrees)——这实际上正是类型错误告诉你的——除了看起来你的代码编译得很好。