【问题标题】:Haskell N-ary tree constructionHaskell N-ary 树构造
【发布时间】:2014-04-18 14:24:25
【问题描述】:

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

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

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

      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]

我们将不胜感激任何类型的 cmets 和答案。

【问题讨论】:

  • 这个问题具体是什么?代码应该做什么,它目前在做什么,与预期有何不同?
  • 这段代码没有采用它在遇到的第一个空列表中停止的列表的所有元素,我知道我的问题实际上在哪里,我需要的是一个算法。所以我无法创建整棵树
  • 这个函数应该做什么还是很难理解。你能给出一个示例输入和所需的输出以及实际输出吗?
  • 输入:listToTree 0 [3,2,9,8,4,5,0,1,6,7] 所需输出节点 3 [节点 2 [空],节点 9 [节点 8 [节点 4],节点 5 [节点 0],节点 1 [空],节点 6 [空],节点 7 [空]]] 我的输出节点 3 [节点 2 [空]]
  • 正如我所说,它停在第一个空节点

标签: haskell recursion syntax tree


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多