简体   繁体   English

获取 Haskell 中玫瑰树的所有路径

[英]Get all paths in a rose tree in Haskell

I have the following implementation of a rose tree:我有以下玫瑰树的实现:

data Rose a = Empty | Branch a [Rose a] deriving (Show, Eq)

So I wanna get all of the paths in the tree, what I have done so far is the following:所以我想得到树中的所有路径,到目前为止我所做的如下:

paths :: Rose a -> [[a]]
paths Empty = [[]]
paths (Branch n []) = [[n]]
paths (Branch n ns) = map ((:) n . concat . paths) ns

This is my tree这是我的树

sample2:: Rose String
sample2 = Branch "/" [Branch "dir1" [Branch "file1" [Empty], Branch "dir3" [Empty]], Branch "dir2" [Branch "file2" [Empty], Branch "file3" [Empty]]]

And the output of paths sample2 is the following: [["/","dir1","file1","dir1","dir3"],["/","dir2","file2","dir2","file3"]]路径 sample2 的 output 如下: [["/","dir1","file1","dir1","dir3"],["/","dir2","file2","dir2","file3"]]

But I want it to be:但我希望它是:

[["/","dir1","file1"],["/", "dir1","dir3"],["/","dir2","file2"],["/", "dir2","file3"]]

How to achieve this result?如何达到这个结果?

You should concatenate the end product, not the paths of the individual childs, so:您应该连接最终产品,而不是单个孩子的paths ,因此:

paths :: Rose a -> [[a]]
paths Empty = [[]]
paths (Branch n []) = [[n]]
paths (Branch n ns) = concatMap (map (n :) . paths) ns
paths :: Rose a -> [[a]] paths Empty = [[]] paths (Branch n ns) = map (n :) (concat $ map paths ns)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM