[英]Folding over Rose Tree
给定以下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)
我如何从Tree a
获得[a]
?
你是说用折纸吗? 您可以得到一个函数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]
我个人认为第一个版本更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.