简体   繁体   English

折叠在玫瑰树上

[英]Folding over Rose Tree

Given the following Algrebaic Data Structure: 给定以下Algrebaic数据结构:

data Tree a = Node {
    rootLabel :: a,
    subForest :: [Tree a]
}  deriving (Show)

and fold : fold

treeFold :: (a -> [b] -> b) -> Tree a -> b
treeFold f (Node x ts) = f x (map (treeFold' f) ts)

How can I get an [a] from a Tree a ? 我如何从Tree a获得[a]

Do you mean using fold? 你是说用折纸吗? You can get a function Tree a -> [a] pretty straightforward: 您可以得到一个函数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]

If you specifically want to use fold , I guess you could do something similar: 如果您特别想使用fold ,我想您可以做类似的事情:

collapse' :: Tree a -> [a]
collapse' = treeFold (\x tss -> x : (concat tss))

Prelude> collapse' t
[3,2,4,6]

I personally think the first version is clearer. 我个人认为第一个版本更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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