【问题标题】:Looking for an example of a typical tree-recursion turned into a tail-recursive form寻找一个典型的树递归变成尾递归形式的例子
【发布时间】:2010-04-22 14:09:50
【问题描述】:

在嵌套列表上的任何东西都可以,比如 flatten、count-atoms 等。

顺便说一句,我对 CPS 转换或“对树”不感兴趣。

【问题讨论】:

    标签: scheme tail-recursion


    【解决方案1】:

    您可以编写一个带有堆栈的循环,该堆栈记录要处理的下一棵树。你还需要一个蓄能器。但这与 CPS 并没有什么不同,因此它可能不是您想要的。

    (define (atom? x) 
      (not (pair? x)))
    (define (size tree)
      (let loop ((t tree) (stack '()) (total 0))
        (cond
          ((and (atom? t) (null? stack)) (add1 total))
          ((atom? t) (loop (car stack) (cdr stack) (add1 total)))
          (else (loop (cadr t) (append (cddr t) stack) (add1 total))))))
    (define (flatten tree)
      (let loop ((t tree) (stack '()) (l '()))
        (cond
          ((and (atom? t) (null? stack)) (reverse (cons t l)))
          ((atom? t) (loop (car stack) (cdr stack) (cons t l)))
          (else (loop (cadr t) (append (cddr t) stack) (cons (car t) l))))))
    

    【讨论】:

    • 这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    相关资源
    最近更新 更多