在 Haskell 中获取玫瑰树中特定父项的所有子项

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 <strong>name == x then xs</strong> else 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 = <strong>names</strong> . childrenOf name