简体   繁体   English

Haskell Nary树结构

[英]Haskell N-ary tree construction

I am new in Haskell. 我是Haskell的新手。 I trying to learn implementation of N-ary trees in Haskell. 我试图学习Haskell中N元树的实现。 I tried to construct N-ary tree and so I create my own data type 我试图构造N元树,所以我创建了自己的数据类型

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

I want to construct my Tree from the list. 我想从列表中构建我的树。 I want to construct such Tree that going to take List elements one by one . 我想构造这样的Tree,它将一个接一个地添加List元素。 If element is smaller it is going to be subtree of previous element else it going to be sibling.My problem is in the base cases and recursion parts. 如果element较小,它将是前一个元素的子树,否则它将是同级。我的问题是在基本情况和递归部分中。 So I write such a code: 所以我写了这样的代码:

      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]

Any kind of comments and answers will be appreciated. 任何意见和答案将不胜感激。

Why does your function take an integer as first argument? 为什么您的函数将整数作为第一个参数? Also it is not clear if the tree should end in "Node int []" or "Node int empty". 还不清楚树是否应该以“ Node int []”或“ Node int empty”结尾。 If you are ready to accept [Tree] as output you don't even need empty which would probably only really be necessary for the empty list. 如果您准备接受[Tree]作为输出,则您甚至不需要为空,这可能仅是真正需要的空列表。 In that case, the function could be as follows. 在那种情况下,功能可以如下。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM