我試圖通過給出節點的父節點的名稱和節點的名稱來從 Haskell 中的玫瑰樹中洗掉一個元素:
我已經寫了這個,但它沒有編譯
deleteNode x parent (Branch x' trees)
| parent == x' = Branch x' $ if (head trees) /= x then ((Branch x []):trees) else []
| otherwise = Branch x' $ (deleteNode x parent) <$> trees
錯誤是:
tree.hs:25:75: error:
* Occurs check: cannot construct the infinite type: t ~ Rose t
Expected type: [Rose (Rose t)]
Actual type: [Rose t]
* In the second argument of `(:)', namely `trees'
In the expression: ((Branch x []) : trees)
In the second argument of `($)', namely
`if (head trees) /= x then ((Branch x []) : trees) else []'
* Relevant bindings include
trees :: [Rose t] (bound at tree.hs:24:32)
x' :: t (bound at tree.hs:24:29)
parent :: t (bound at tree.hs:24:14)
x :: Rose t (bound at tree.hs:24:12)
deleteNode :: Rose t -> t -> Rose t -> Rose t
(bound at tree.hs:24:1)
Failed, modules loaded: none.
我對玫瑰樹有以下定義
data Rose a = Empty | Branch a [Rose a] deriving (Show, Eq)
如何使其作業并回傳不包含指定元素的新樹?
uj5u.com熱心網友回復:
我不清楚你為什么需要parent這里。您可以將視圖實作為:
deleteNode :: Eq a => a -> Rose a -> Rose a
deleteNode _ Empty = Empty
deleteNode x (Branch x' trees)
| x == x' = Empty
| otherwise = Branch x' $ (deleteNode x) <$> trees
如果我們因此找到了專案 ( x == x'),那么我們回傳Empty,否則我們在葉子上遞回。
請注意,此功能將洗掉所有具有x“標簽”的分支,因此如果有多個目錄foo/,它將洗掉所有目錄。
如果parent是parent節點的名稱,您可以使用:
deleteNode :: Eq a => a -> a -> Rose a -> Rose a
deleteNode _ _ Empty = Empty
deleteNode parent x (Branch x' trees)
| parent == x' = Branch x' (map (go x) trees)
| otherwise = Branch x' $ (deleteNode parent x) <$> trees
where go _ Empty = Empty
go x b@(Branch x' _)
| x == x' = Empty
| otherwise = b
這將洗掉所有具有作為父標簽Branchvalueparent和x作為自己 value 的專案。然而,樹中仍然可以有多個專案foo作為父項和bar標簽,以便將這些專案全部洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/406347.html
標籤:
