這個問題在這里已經有了答案: 在 Haskell 4 答案 中,從左到右對樹中所有出現的葉子進行編號 5 天前關閉。
說我有一個Data.Tree控股字符Tree Char::
A
/ \
B C
/|\
D A F
請注意,在樹中可能有重復項。我想通過存盤邊將這棵樹存盤在關系資料庫中,但由于重復,我不能使用節點的內容作為鍵(注意A不同級別的)。
也許一個解決方案是遍歷樹并使用唯一的 id 映射它,例如:
(1,A)
/ \
(2,B) (3,C)
/|\
(4,D)(5,A),(6,F)
現在存盤邊緣沒有任何問題,因為我使用了 id。
(1, null, A)
(2, 1, B)
(3, 1, C)
(4, 3, D)
(5, 3, A)
(6, 3, F)
但我看不到如何將靜態樹節點“映射”到無限 id 生成器。
從功能的角度來看,您的方法是什么?請注意,我無法對分支因子的數量做出任何假設,因此我無法展平、使用 id 壓縮并重建樹
uj5u.com熱心網友回復:
您可以使用State將發送 id 的 a,因此:
import Control.Monad.State.Lazy(State, get, put)
labelNext :: State Int Int
labelNext = do
val <- get
put (val 1)
return val
然后我們可以用以下方式標記樹:
{-# LANGUAGE TupleSections #-}
labelTree :: Tree a -> Tree (Int, a)
labelTree tree = evalState (traverse (\a -> (,a) <$> labelNext) tree) 1
例如,這給了我們:
ghci> labelTree (Node 'A' [Node 'B' [], Node 'C' [Node 'D' [], Node 'A' [], Node 'F' []]])
Node {rootLabel = (1,'A'), subForest = [Node {rootLabel = (2,'B'), subForest = []},Node {rootLabel = (3,'C'), subForest = [Node {rootLabel = (4,'D'), subForest = []},Node {rootLabel = (5,'A'), subForest = []},Node {rootLabel = (6,'F'), subForest = []}]}]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434060.html
