如何在Haskell
问题描述:
在列表树的落叶归我到目前为止这样的代码:如何在Haskell
data BinaryTree a = Null | Node a (BinaryTree a) (BinaryTree a)
treeLeaves :: BinaryTree a -> [a]
treeLeaves tree = case tree of
Null -> []
Node v t1 t2 -> [] ++ treeLeaves t1 ++ treeLeaves t2
我不知道我做错了。它输出一个空的列表。
答
现在你错过了将叶子添加到列表中的重要步骤,这就是为什么你总是得到一个空列表。当Zeta评论时,[] ++ treeLeaves t1 ++ treeLeaves t2
最终将落入Null
分支并成为[] ++ [] ++ ... ++ []
。
当BinaryTree
是Node v Null Null
时,你知道你已经到了叶。所以,你需要编写这种情况下,一个分支太:
treeLeaves :: BinaryTree a -> [a]
treeLeaves tree = case tree of
Null -> []
Node v Null Null -> v:[]
Node _ t1 t2 -> treeLeaves t1 ++ treeLeaves t2
正如伊戈尔评论,你可以在最后一行,因为你没有使用元素在该节点使用_
代替v
(因为它不是一个叶)。
在写入Haskell之前,请先解释一下你自己会怎么做?您希望程序采取哪些步骤来返回树叶? –
'[] ++ x ++ y'是'x ++ y'。 'treeLeaves'在什么时候返回别的不是'[]'? – Zeta
来自'Node v t1 t2'的'v'参数在实现中不使用。嗯,也许我们可以用它做点什么,或者用'_'代替不要分心...... –