我有以下玫瑰樹的實作:
data Rose a = Empty | Branch a [Rose a] deriving (Show, Eq)
所以我想獲得樹中的所有路徑,到目前為止我所做的如下:
paths :: Rose a -> [[a]]
paths Empty = [[]]
paths (Branch n []) = [[n]]
paths (Branch n ns) = map ((:) n . concat . paths) ns
這是我的樹
sample2:: Rose String
sample2 = Branch "/" [Branch "dir1" [Branch "file1" [Empty], Branch "dir3" [Empty]], Branch "dir2" [Branch "file2" [Empty], Branch "file3" [Empty]]]
路徑 sample2 的輸出如下: [["/","dir1","file1","dir1","dir3"],["/","dir2","file2","dir2","file3"]]
但我希望它是:
[["/","dir1","file1"],["/", "dir1","dir3"],["/","dir2","file2"],["/", "dir2","file3"]]
如何達到這個結果?
uj5u.com熱心網友回復:
您應該連接最終產品,而不是paths單個孩子的產品,因此:
paths :: Rose a -> [[a]]
paths Empty = [[]]
paths (Branch n []) = [[n]]
paths (Branch n ns) = concatMap (map (n :) . paths) ns
uj5u.com熱心網友回復:
paths :: Rose a -> [[a]]
paths Empty = [[]]
paths (Branch n ns) = map (n :) (concat $ map paths ns)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/394584.html
標籤:哈斯克尔
