Haskell N-ary树建设

时间:2014-03-13 16:56:23

标签: haskell recursion syntax tree

我是Haskell的新手。我试图在Haskell中学习N-ary树的实现。我尝试构建N-ary树,因此我创建了自己的数据类型

      data Tree = Empty | Node Integer [Tree] deriving Show

我想从列表中构建我的树。我想构建一个这样的Tree,它将逐个获取List元素。如果元素较小,它将成为前一个元素的子树,否则它将成为兄弟。我的问题在于基本情况和递归部分。所以我写了这样的代码:

      arrin :: [Integer] -> Integer -> Integer {-this function takes an array -}
      arrin (x:xs) i                           {- and indexs and return the element-}  
        | i == 0    = x                    {-of that array which on that index -}
        | otherwise = arrin xs (i-1)  


      listToTree :: Integer -> [Integer] -> Tree
      listToTree _ [] = Empty {-First Input will be zero initially-}
      listToTree 11 _ = Empty {-Lets assume that the lenght of my list is 10-}
      listToTree 0 a = Node ( arrin a 0 ) [listToTree 1 a]
      listToTree num a  {-I need your help in this part what should i do-}
          | arrin a num > arrin a (num+1) = Node ( arrin a num ) [listToTree (num+1) a]
          | otherwise = Node ( arrin a num ) [Empty]

任何形式的评论和答案都将不胜感激。

1 个答案:

答案 0 :(得分:1)

为什么你的函数将整数作为第一个参数?此外,还不清楚树是否应以“Node int []”或“Node int empty”结尾。如果您准备接受[Tree]作为输出,您甚至不需要空,这可能只对空列表真正需要。在这种情况下,功能可以如下。

listToTree :: [Integer] -> [Tree]
listToTree [] = []
listToTree [x] = [Node x []]
listToTree (x1:x2:xs)
    | x2 < x1 = [Node x1 (listToTree (x2:xs))] -- subtree
    | otherwise = Node x1 [] : listToTree (x2:xs) -- sibling