简体   繁体   中英

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"]]

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 :: 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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