需要折叠树的帮助

问题描述 投票:0回答:1

我正试着走树,把每条路都变成一个列表。这是我的结构。我称它为Unigraph,因为它是一个单向图。如果我使用不正确的术语,请道歉。

data Unigraph a = Node a [Unigraph a] deriving (Show)

基本上,我试图描述这样的结构:

       1
     / | \
    2  3  4
   / \  \
  3   4  4

我有以下功能:

comboGraph :: [a] -> Int -> [Unigraph a]
comboGraph _ 0 = []
comboGraph [] _ = []
comboGraph (x:xs) n =
    buildEdge x xs : (comboGraph xs n)
    where   buildEdge h t = Node h (comboGraph t (n-1))

对于给定的列表和整数n,我可以用Unigraph深度创建一个n

所以上面的图可以通过运行来创建

let ug = head $ comboGraph [1..4] 3

这是我正在努力解决的问题。我想将给定的Unigraph转换为路径列表,即[[1,2,3], [1,2,4], [1,3,4], [1,4]]

这是我到目前为止所拥有的:

getAllPaths :: Unigraph a -> [[a]]
getAllPaths (Node _ []) = []
getAllPaths (Node a (x:xs)) =
    getAllPaths x ++ getAllPaths' xs
    where   getAllPaths' (y:ys) = getAllPaths y ++ getAllPaths' ys
            getAllPaths' [] = []

但是这个功能并没有考虑到任何地方节点的价值!我被困在这里了。我该怎么做呢?

haskell
1个回答
0
投票

在基本情况下,您需要返回节点值

在递归的情况下 - 将节点值预先添加到每个子路径

getAllPaths :: Unigraph a -> [[a]]
getAllPaths (Node a []) = [[a]]
getAllPaths (Node a children) = map (a:) (concatMap getAllPaths children)
© www.soinside.com 2019 - 2024. All rights reserved.