[英]flatten a tree with a list of subtrees in Haskell
I would like to flatten a tree which looks like this: 我想展平一棵看起来像这样的树:
> data Tree a = Leaf a
> | Fork a [Tree a]
> | Root [Tree a]
possible example: 可能的例子:
Root [Fork 'a' [Fork 'b' [Leaf 'c'],Fork 'c' [Leaf 'b']],Fork 'b' [Fork 'a' [Leaf 'c'],Fork 'c' [Leaf 'a']],Fork 'c' [Fork 'a' [Leaf 'b'],Fork 'b' [Leaf 'a']]]
should become 应该成为
["abc","acb","bac","bca","cab","cba"]
To explain why: I try to build kind of a permutation Tree. 解释原因:我尝试构建一种置换树。 I wrote a function
permute :: String -> Tree Char
to visualize all possible permutations of an string into a Tree. 我写了一个函数
permute :: String -> Tree Char
来可视化字符串到Tree的所有可能排列。 But I dont get how to flatten this kind of tree. 但是我不知道如何弄平这种树。 Thank you for help.
谢谢你的帮助。
My approach here comes out to a depth first search. 我这里的方法是深度优先搜索。
data Tree a = Leaf a
| Fork a [Tree a]
| Root [Tree a]
deriving(Show)
dfs :: Tree a -> [[a]]
dfs (Root ts) = concatMap dfs ts
dfs (Fork v ts) = map (v:) (concatMap dfs ts)
dfs (Leaf v) = [[v]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.