鉴于以下Algrebaic数据结构:
data Tree a = Node {
rootLabel :: a,
subForest :: [Tree a]
} deriving (Show)
和fold
:
treeFold :: (a -> [b] -> b) -> Tree a -> b
treeFold f (Node x ts) = f x (map (treeFold' f) ts)
如何从[a]
获得Tree a
?
答案 0 :(得分:3)
你的意思是使用折叠吗?您可以非常简单地获得函数Tree a -> [a]
:
collapse :: Tree a -> [a]
collapse (Node x ts) = x : (concat $ map collapse ts)
Prelude> let t = Node 3 [Node 2 [], Node 4 [], Node 6 []]
Prelude> collapse t
[3,2,4,6]
如果你特别想使用fold
,我想你可以做类似的事情:
collapse' :: Tree a -> [a]
collapse' = treeFold (\x tss -> x : (concat tss))
Prelude> collapse' t
[3,2,4,6]
我个人认为第一个版本更清晰。