[英]Get all of the children of a specific parent in a rose tree in Haskell
我正在尝试通过 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.
您可以通过以下方式获取给定目录的子目录:
childrenOf:: Eq a => a -> Rose a -> [Rose a] childrenOf _ Empty = [] childrenOf name (Branch x xs) = if !!!name == x then xs!!! 否则 concatMap (childrenOf name) xs
这将生成具有给定名称的所有Branch
的直接分支作为Rose
元素。 您还可以通过以下方式获取相应的名称:
names :: [Rose a] -> [a]
names xs = [ x | Branch x _ <- xs ]
namesOfChildren :: Eq a => a -> Rose a -> [a]
namesOfChildren name = names . childrenOf name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.