簡體   English   中英

折疊在玫瑰樹上

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM