【问题标题】:Outputting different levels in a nested list在嵌套列表中输出不同的级别
【发布时间】:2014-12-14 08:00:13
【问题描述】:

在我参加考试之前试图弄清楚这一点的快速问题。

如果我有一个嵌套列表,例如

(list 1 (list 2 3 ( list 4 (list 6))))

我将如何编写一个只给我最低级别或第 3 级别的函数?

例如,最低层将输出'(6),第三层将输出'(4)

我在争论是否可以使用平板,但我不知道水平。

任何帮助将不胜感激。

【问题讨论】:

  • 添加一些代码以表明您已经尝试过并更容易为您提供帮助。

标签: scheme racket


【解决方案1】:

使用递归下降并将当前级别作为额外参数传递。

(define (collect s-exp level) ...)

 1. If s-exp is empty return '()
 2. If s-exp is a pair, (cons a d), then
    2a. if a is a pair, then recurse on a with an increased level
    2b. if level is below 3
          3a recurse on a
          3b recurse on d
          3c. append the results from 3a and 3b
    2c  if level is 3
          4a recurse on d
          4b append (list a) with the result from 4a

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多