1

int リストから可能なすべてのツリーを生成したいのですが、生成する[Int] -> [T]ツリーは 1 つだけです。

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

-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 に答える