[英]Haskell summarize all paths through a tree
I try to summarize ALL paths though a tree that expands every level between 1 and 10 times from the root to the lowest children. 我试图总结所有路径,通过一个树,从根到最低的孩子,每个级别扩展1到10倍。 My function walks recursive to all children but I have the problem that when I try to make a List of the nodes and do this lists in a list, I become a List of a List of a List ... of a List.
我的函数遍历所有孩子,但我遇到的问题是,当我尝试创建节点列表并在列表中执行此列表时,我成为列表列表的List ...列表。 I think my problem is the combining step And I tried to make a pattern matching method but the method that should compare the lists when it becomes a lists of lists and should make new lists and compare them if it get's just one way( meets a list with the nodes and not a list with lists) doesn't work.
我认为我的问题是组合步骤我尝试制作模式匹配方法,但是当它成为列表列表时应该比较列表的方法,并且应该创建新列表并比较它们,如果它只是一种方式(满足列表)使用节点而不是带列表的列表)不起作用。
summarize :: Tree a -> [[a]]
summarize Leaf = [[]]
summarize (Node a t1 t2) = do
t <- [t1, t2]
map (a:) (summarize t)
Edit: Note that the above assumes the following definition for Tree
: 编辑:请注意,上面假设
Tree
的以下定义:
data Tree a = Leaf | Node a (Tree a) (Tree a)
Edit #2: This version of the code might be clearer: 编辑#2:此版本的代码可能更清晰:
summarize :: Tree a -> [[a]]
summarize Leaf = [[]]
summarize (Node a t1 t2) = do
t <- [t1, t2]
summary <- summarize t
return (a:summary)
This version has the nice property that it can be written as a list comprehension: 这个版本有一个很好的属性,它可以写成列表理解:
summarize (Node a t1 t2) = [a:summary | t <- [t1, t2], summary <- summarize t]
A tree can be represented as a list-monadic-list (a list where there are several options for how it resumes at each point). 树可以表示为list-monadic-list(一个列表,其中有几个选项可以在每个点恢复它)。 Then, what you want is simply a fold on this monadic list.
然后,你想要的只是这个monadic列表的折叠。
import Control.Monad.Trans.List.Funcs (repeatM) -- cabal install List
import qualified Data.List.Class as L
exampleTree = L.take 3 (repeatM [0, 1])
To see all paths: 要查看所有路径:
ghci> L.toList exampleTree
[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
To sum all paths: 总结所有路径:
ghci> L.foldlL (+) 0 exampleTree
[0,1,1,2,1,2,2,3]
Wrt this representation of trees, the ListTree package offers combinators for tree operations (such as DFS/BFS iteration) on trees represented as ListT []
s. 对于树的这种表示, ListTree包为表示为
ListT []
s的树提供树操作(例如DFS / BFS迭代)的组合器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.