Given the following Algrebaic Data Structure:
data Tree a = Node {
rootLabel :: a,
subForest :: [Tree a]
} deriving (Show)
and 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
?
Do you mean using fold? You can get a function Tree a -> [a]
pretty straightforward:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.