我有一个数据类型:
data Tree = Empty | Node Int Tree Tree
我想要功能
nodeDepth :: Tree -> [(Int, Int)]
每个节点一对。第一个元素是label(值),第二个元素是其深度。
我的意图(原始代码)是这样的:
nodeDepth (Node label left right) = zip nodeDepth' (Node label left right) [0]
nodeDepth' Empty _ = []
nodeDepth' (Node label left right) [level] = label : nodeDepth' (Node label left right) level : (1 + level)
但这是行不通的。
怎么了?我正在使用Frege REPL
Error message are like :
E <console>.fr:22: t19906 occurs in type [t19906] rendering expression level{19727} untypable.
E <console>.fr:22: type error in expression level
type is t19906
used as [t19906]
E <console>.fr:22: type error in expression
nodeDepth' (Node label left right) level:+ 1 level
type is [[t19909]]
used as [Int]
E <console>.fr:22: [[Int]] is not an instance of Num
E <console>.fr:20: type error in expression nodeDepth'
type is apparently [t19961]
used as function
H <console>.fr:20: too many or too few arguments perhaps?
E <console>.fr:20: type error in expression Node label left right
type is Tree
used as [t19964]
E <console>.fr:20: type error in expression
zip nodeDepth' (Node label left right)
type is apparently [(t19961,t19964)]
used as function
H <console>.fr:20: too many or too few arguments perhaps?
W <console>.fr:20: application of nodeDepth will diverge.
至于错误,请考虑以下行:
nodeDepth (Node label left right) = zip nodeDepth' (Node label left right) [0]
由于Haskell功能应用程序与左侧关联,因此zip将功能nodeDepth'作为其第一个参数。要解决此特定错误,您可能需要编写:
zip (nodeDepth' (Node label left right)) [0]
但是然后您仍然缺少nodeDepth'的第二个参数,因此括号中的表达式仅返回函数而不是列表。
另一个错误是为非空树定义nodeDepth'时:模式匹配[level]将level捕获为单个元素,并将其传递给同一行。这只能通过假设级别本身是一个列表来解决,但这也没有太大意义,因为在该行的末尾,添加内容假定级别为数字类型。
nodeDepth' (Node label left right) [level] = label : nodeDepth' (Node label left right) level : (1 + level)
以下函数nodeDepth使用深度优先搜索遍历树,并构造标签列表和各个节点的深度。
data Tree = Empty | Node Int Tree Tree
wikiTree = Node 2 (Node 7 (Node 2 Empty Empty) (Node 6 (Node 5 Empty Empty) (Node 11 Empty Empty))) (Node 5 Empty (Node 9 (Node 4 Empty Empty) Empty))
nodeDepth :: Tree -> [(Int, Int)]
nodeDepth Empty = []
nodeDepth (Node label left right) = nodeDepthAccumulator (Node label left right) 0
nodeDepthAccumulator :: Tree -> Int -> [(Int, Int)]
nodeDepthAccumulator Empty _ = []
nodeDepthAccumulator (Node label left right) depth = (label,depth) : nodeDepthAccumulator left (depth+1) ++ nodeDepthAccumulator right (depth+1)
在示例WikiTree上执行nodeDepth,您将获得:
> nodeDepth wikiTree
> [(2, 0),(7, 1),(2, 2),(6, 2),(5, 3),(11, 3),(5, 1),(9, 2),(4, 3)]
如您所料。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句