【问题标题】:Haskell: List to Rose TreeHaskell:玫瑰树列表
【发布时间】:2014-02-08 00:31:26
【问题描述】:

考虑以下类型来表示玫瑰树:

data RTree a = No a [RTree a]

考虑函数

tolist a = tolistAux 1 a
     where tolistAux n (No x l) = (x,n) : (concat (map (tolistAux (n+1)) l))

我需要定义第一个函数的逆:unlist :: [(a,Int)] -> RTree a

这样unlist (tolist a) = a

【问题讨论】:

  • 这与您之前的问题非常相似,我相信您无需额外输入即可通过执行此作业步骤了解更多信息。请认真思考你之前的问题,以及为什么你的导师在这个问题之前提出了这个问题。
  • @enoughreptocomment 我提出了一个可能的解决方案。我怎么能在这里重新调整我以前的问题的解决方案?有什么想法吗?

标签: list haskell tree higher-order-functions


【解决方案1】:

这是我找到的解决方案。

我意识到如果在 (a,b), b==1 那么我创建一个 No a (...) 因此,我有一个列表并将这个列表隔离为几个以 (a,1) 开头的列表,方法是首先将 1 减去 b。 然后,我使用递归(例如映射函数)创建树:

unlist ((x,1):t) = No x l3
where l1 = map (\(a,b) -> (a,b-1)) t
  l2 = isolate1 l1
  l3 = map unlist l2

isolate1 :: [(a,b)]->[[(a,b)]] --note that the result of isolate1 is a list of lists of pairs
isolate1 [] = []
isolate [x]=[[x]]
isolate1 ((a,b):t) = let (x:xs):ys = isolate1 t  
                     in |b==1 = ((a,b):x:xs):ys
                        |otherwise = [(a,b)]:(x:xs):ys

很高兴看到更多解决方案:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多