簡體   English   中英

Haskell Nary樹結構

[英]Haskell N-ary tree construction

我是Haskell的新手。 我試圖學習Haskell中N元樹的實現。 我試圖構造N元樹,所以我創建了自己的數據類型

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

我想從列表中構建我的樹。 我想構造這樣的Tree,它將一個接一個地添加List元素。 如果element較小,它將是前一個元素的子樹,否則它將是同級。我的問題是在基本情況和遞歸部分中。 所以我寫了這樣的代碼:

      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]

任何意見和答案將不勝感激。

為什么您的函數將整數作為第一個參數? 還不清楚樹是否應該以“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM