【问题标题】:Depth of list in scheme方案中的列表深度
【发布时间】:2015-02-04 20:13:28
【问题描述】:

我正在尝试编写一个程序来查找列表的最大深度。到目前为止我的代码是:


(define (depth l)
  (define (helper l count)
    ( cond
        ((null? l) count)
        ((not(list? (car l))) (helper (cdr l) count))
        (else (helper (car l) (+ count 1)) )
    )
  )
  (helper l 1)
) 

它适用于(depth '(1 2 3 (2))) -> 2 类型的列表,但显然不适用于(depth '( (2) ((3))) -> 3 类型的列表。问题是当我第一次遇到一个列表时,我会自动跳转到它增加计数并再次递归调用它,而忽略列表的其他元素。我想解决这个问题,我想添加另一个变量temp 来保存列表中每个元素的当前计数并检查它是否大于count,如果是真的我set!counttemp,但我又遇到了递归问题。我的另一个想法是使用另一个列表来appendcount 在每个步骤中找到该列表中的最大值,但我也没有意识到这一点。任何想法如何解决这个问题?

【问题讨论】:

    标签: list recursion scheme racket


    【解决方案1】:

    这是一个使用map的实现:

    (define (max-depth l)
      (define (helper depth el)
        (cond
          [(null? el) (add1 depth)]
          [(list? el)
           (apply max
                   (map (curry helper (add1 depth))
                        el))]
          [else depth]))
      (helper 0 l))
    

    虽然我认为这个实现相当优雅,但不可否认它不是尾递归的。

    这是一个稍微复杂的、广度优先的尾递归实现:

    (define (max-depth l)
      (define (helper depth els)
        (define remaining (filter list? els))
        (if (zero? (length remaining))
            depth
            (helper (add1 depth) (apply append remaining))))
      (helper 1 l))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多