我正在嘗試通過 Haskell 中的給定名稱獲取特定根的所有子項。
樹的宣告:
data Rose a = Empty | Branch a [Rose a] deriving (Show, Eq)
sample2:: Rose String
sample2 = Branch "/" [ Branch "dir1" [ Branch "file1" [Empty]
, Branch "dir3" [Empty]]
, Branch "dir2" [ Branch "file2" [Empty]
, Branch "file3" [Empty]]]
以及我嘗試過的:
childrenOf _ Empty = []
childrenOf name (Branch x xs) = if name == x then xs else childrenOf name xs
我想打電話childrenOf "dir1" sample2給["file1", "dir3"]
但是,我收到錯誤訊息:
[1 of 1] Compiling Main ( tree.hs, interpreted )
tree.hs:47:1: error:
* Couldn't match type Rose t' with [Rose t]'
Expected type: t -> [Rose t] -> [Rose t]
Actual type: t -> Rose t -> [Rose t]
* Relevant bindings include
childrenOf :: t -> [Rose t] -> [Rose t] (bound at tree.hs:47:1)
Failed, modules loaded: none.
uj5u.com熱心網友回復:
您可以通過以下方式獲取給定目錄的子目錄:
childrenOf :: Eq a => a -> Rose a -> [Rose a] childrenOf _ Empty = [] childrenOf name (Branch x xs) = if !!!name == x then xs!!! else concatMap (childrenOf name) xs
這將產生所有具有給定名稱作為元素的es的直接分支。您還可以通過以下方式獲取相應的名稱:BranchRose
names :: [Rose a] -> [a]
names xs = [ x | Branch x _ <- xs ]
namesOfChildren :: Eq a => a -> Rose a -> [a]
namesOfChildren name = names . childrenOf name
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394426.html
標籤:哈斯克尔
