【发布时间】:2018-03-01 08:52:12
【问题描述】:
我正在尝试走一棵树并将每条路径变成一个列表。这是我的结构。我称它为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,我可以创建一个具有 n 深度的 Unigraph。
所以上面的图可以通过运行来创建
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' [] = []
但是这个函数在任何地方都没有考虑到节点的值!我被困在这里了。我该怎么做?
【问题讨论】:
-
您的
Node a (x:xs)子句不使用a。您可能还希望[[]]作为另一个子句中的基本情况......或者可能是[[a]]和a的值Node。
标签: haskell