1

我想从一个 int 列表中生成所有可能的树,[Int] -> [T]但我只生成一棵树。

1           1
2           2
3           5
4          14
5          42

像这些加泰罗尼亚数字。如果我的列表大小是 3,我想生成 5 棵可能的树,如果是 4 - 14 棵可能的树。

代码:

data T = N T T | L Int deriving (Show)
toT :: [Int] -> T
toT [] = L 0
toT [n] = L n
toT ns = T (toT (take mid ns)) (toT (drop (mid+1) ns))
where
mid = length ns div 2

例如:toT [1..3]

输出:N (L 1) (N (L 2) (L 3))N (N (L 1) (L 2)) (L 3)

现在我确实喜欢这样

     toTree [] = error "!!"
     toTree [n] = Leaf n
     toTree ns = Node leftTree rightTree
     where 
     leftTree = toTree $ take (length(ns)-1) ns
     rightTree = toTree $ drop (length(ns)-1) ns` ı want ns length contiue descend one point recursive but ı didnt

我怎样才能做到这一点 ?在递归中我将发送相同的列表但长度将下降我再次发送 [1,2,3] 大小 3 我发送 [1,2,3] 长度 2

4

2 回答 2

1

需要发生的是,列表需要在每个可能的点进行拆分,这样做会使列表更小。需要累积子列表的树,然后将所有内容组合起来。

data Tree
  = L {-# UNPACK #-} !Int
  | N !Tree !Tree
  deriving (Eq, Ord, Read, Show)

-- Convert a list of Ints into a list of Trees containing the given list.
toTrees :: [Int] -> [Tree]

-- We start with the base cases: 0 and 1 elements. Because there are no
-- trees of 0 length, it returns the empty list in that case.
toTrees [] = []
toTrees [x] = [L x]

-- There is at least two elements in this list, so the split into nonempty
-- lists contains at least one element.
toTrees (x:xs@(y:ys)) = let
  -- splitWith uses a difference list to accumulate the left end of the
  -- split list.
  splitWith :: ([a] -> [a]) -> [a] -> [([a], [a])]
  splitWith fn [] = []
  splitWith fn as@(a:as') = (fn [], as):splitWith (fn . (:) a) as'

  -- Now we use a list comprehension to take the list of trees from each
  -- split sublist.
  in [
    N tl tr |
    (ll, lr) <- ([x], xs):splitWith ((:) x . (:) y) ys,
    tl <- toTrees ll,
    tr <- toTrees lr
  ]

这给出了预期的结果:

GHCi> toTrees [1, 2, 3, 4, 5]
[N (L 1) (N (L 2) (N (L 3) (N (L 4) (L 5)))),N (L 1) (N (L 2) (N (N (L 3) (L 4)) (L 5))),
 N (L 1) (N (N (L 2) (L 3)) (N (L 4) (L 5))),N (L 1) (N (N (L 2) (N (L 3) (L 4))) (L 5)),
 N (L 1) (N (N (N (L 2) (L 3)) (L 4)) (L 5)),N (N (L 1) (L 2)) (N (L 3) (N (L 4) (L 5))),
 N (N (L 1) (L 2)) (N (N (L 3) (L 4)) (L 5)),N (N (L 1) (N (L 2) (L 3))) (N (L 4) (L 5)),
 N (N (N (L 1) (L 2)) (L 3)) (N (L 4) (L 5)),N (N (L 1) (N (L 2) (N (L 3) (L 4)))) (L 5),
 N (N (L 1) (N (N (L 2) (L 3)) (L 4))) (L 5),N (N (N (L 1) (L 2)) (N (L 3) (L 4))) (L 5),
 N (N (N (L 1) (N (L 2) (L 3))) (L 4)) (L 5),N (N (N (N (L 1) (L 2)) (L 3)) (L 4)) (L 5)]
GHCi> length it
14
于 2017-04-12T16:38:33.517 回答
-2

我更新了你的代码,它似乎对我有用。你能检查一下这是否符合你的期望吗?

import Data.List

data Tree = Node Tree Tree | Leaf Int deriving (Show)

toTree :: [Int] -> Tree
toTree [] = Leaf 0
toTree [n] = Leaf n
toTree ns = Node leftTree rightTree
    where midIndex = (length ns) `div` 2
          leftTree = toTree $ take midIndex ns
          rightTree = toTree $ drop (midIndex+1) ns

allTrees :: [Int] -> [Tree]
allTrees xs = map toTree $ permutations xs

main = print $ allTrees [1..4]
于 2016-04-14T17:56:12.987 回答