折叠在玫瑰树

时间:2014-11-14 04:10:06

标签: haskell

鉴于以下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

1 个答案:

答案 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]

我个人认为第一个版本更清晰。