1

这是我对深度程序的了解,但是如何在没有 max 函数的情况下执行此操作(仅使用 define、lambda、quote (')、car、cdr、cons、cond、eq? 和 equal?)?

(define depth
     (lambda (expr)
        (cond ((null? expr) 0) 
              ((list? (car expr)) 
               (max (+ 1 (depth (car expr))) (depth (cdr expr)))) 
              ((null? (cdr expr))0) (max (depth (cdr expr))))))

输入: ((id = id + id)(if bool then (if bool then (id = id + id))(id = const / const)(id = id + id))(while bool (id = id - const )(id = id - id)))

应该输出:最大深度:2

4

1 回答 1

1

好吧,您总是可以实现自己的my-max并使用它而不是内置max过程:

(define (my-max a b)
  (if (> a b) a b))

您必须以一种或另一种方式进行基本相同的比较,才能找到最大深度 - 因此可以将其重构为辅助程序。请注意,内联比较不是一个好主意,因为这将需要计算两次递归调用 - 最好坚持使用辅助过程,无论是它max还是my-max.

此外,您的代码中不需要第二次调用max- 如果只有一个值,为什么需要找到最大值?

于 2012-12-03T03:39:15.937 回答