【发布时间】:2019-10-02 15:40:03
【问题描述】:
我有以下数据类型
data Tree a -> Node a [Tree a]
并且想找到所有节点的标签和树的高度。
这是我所做的:
height:: Tree a -> Integer height
(Node _ (x:xs)) = 1 + maximum height' (x:xs)
height' (x:xs) = map height (x:xs)
我希望 height' 会返回映射到 x:xs 上的高度列表并尝试找到该值的最大值,但 ghci 不同意这里的 map 函数。
【问题讨论】:
-
“失败,因为 xs 是一个树列表,而不是函数类型签名所指示的单个树” - 那么为什么要将
labels应用于列表xs?你想把它应用到这个列表的每个元素上,而真正做到这一点的函数是......?您也不需要在`labels 中将x与xs分开。 -
因为我不确定如何应用到列表中的每个元素而不是整个列表..
-
你快到了。你应该在你的列表中
map这个函数:labels (Node label children) = label : (map labels children) -
我之前尝试过这样做,但收到错误消息:
Occurs check: cannot construct the infinite type: a ~ [a] Expected type: [a] Actual type: [[a]] -
我建议你在另一个问题中添加标签功能,全栈错误