返回嵌套列表的嵌套深度n上的所有元素

时间:2012-11-11 19:58:09

标签: list scheme nested racket depth

我真的很困惑如何做到这一点...我甚至无法弄清楚如何开始,我知道如何为二叉树做这件事,但我希望能够以任何形式做到这一点嵌套列表,有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

对于这个,您需要使用模板遍历任意嵌套的元素列表。例如,研究复制任意嵌套列表的此过程:

(define (copy lst)
  (cond ((null? lst)                ; if list is empty
         '())                       ; return the empty list
        ((not (list? (car lst)))    ; if current element is not a list
         (cons (car lst)            ; cons current element
               (copy (cdr lst))))   ; with the rest of the list
        (else                       ; if current element is a list
         (cons (copy (car lst))     ; cons recursive call over current element
               (copy (cdr lst)))))) ; with recursive call over rest of the list

首先是一点点约定。假设1是基本级别,并且返回的所有元素都将位于平面输出列表中(不保留输入列表的原始结构)。例如:

(elements-level '(1 2 3) 1)
; => '(1 2 3)

(elements-level '(1 (2) 3) 2)
; => '(2)

考虑到上述模板,让我们看看我们如何修改它来解决手头的问题。我会让你填补空白,因为问题看起来像是家庭作业:

(define (elements-level lst lvl)
  (cond ((or (null? lst) (< lvl 1))        ; if list is empty or below level
         '())                              ; return the empty list
        ((not (list? (car lst)))           ; if current element is not a list
         (if (= lvl <???>)                 ; if `lvl` is the base level
             (cons <???>                   ; cons current element in list
               (elements-level <???> lvl)) ; and advance recursion over cdr part
             (elements-level <???> lvl)))  ; else advance recursion over cdr part
        (else                              ; if current element is a list
         (append                           ; use `append` for flattening the list
          (elements-level <???> <???>)     ; recur over car, decrease one level
          (elements-level <???> <???>))))) ; recur over cdr, keep the same level

使用此列表测试过程,它必须返回级别'(1)的{​​{1}},级别1的{​​{1}},依此类推:

'(2)

答案 1 :(得分:0)

我认为您可以使用以下步骤进行递归:

  1. 定义一个列表以保存第n个深度的所有元素。
  2. 创建一个递归函数,以nested listnew listn作为参数
  3. 对于嵌套循环的每个元素,通过将子列表和深度传递为n-1来调用递归函数本身。
  4. 当n = 0时,将nested list的所有元素添加到new list
  5. 完成此方法后,您将n中的所有深度new list元素。

    可能的改进: 如果某些列表元素可能不会扩展到第n级,那么您可能需要在调用递归方法之前检查元素的类型。如果它是leaf类型,那么只需在新列表中添加元素。