用于检查树之间的平等的功能

时间:2010-12-08 03:48:20

标签: tree scheme equality

如何在Scheme中实现一个带有2个树的相等函数,并检查它们是否具有相同的元素和结构?

3 个答案:

答案 0 :(得分:3)

从每个树的根递归 如果根值相似 - 继续左子树,然后右子树 任何差异 - 休息

答案 1 :(得分:1)

我们可以使用相等吗?

 (equal? '(a (b (c))) '(a (b (c))))

但是,为了一些乐趣,继Vassermans提到“休息”之后,这可能是利用Schemes持续控制力的好机会!

如果我们发现树木存在任何差异,我们可以使用 call / cc 来发出提前退货。这样我们就可以跳回到调用者的延续,而不必展开堆栈。

这是一个非常简单的例子。它假定树木结构良好,只包含符号作为叶子,但它应该有希望展示这个概念。您将看到该过程明确接受将continuation作为参数。

 (define (same? a b return)
   (cond
     ((and (symbol? a) (symbol? b))      ; Both Symbols. Make sure they are the same.
       (if (not (eq? a b))
         (return #f)))
     ((and (empty? a) (empty? b)))       ; Both are empty, so far so good.
     ((not (eq? (empty? a) (empty? b)))  ; One tree is empty, must be different!
       (return #f))
     (else
       (begin
         (same? (car a) (car b) return)  ; Lets keep on looking.
         (same? (cdr a) (cdr b) return)))))

call / cc 让我们捕获当前的延续。以下是我调用此过程的方法:

 (call/cc (lambda (k) (same? '(a (b)) '(a (b)) k)))                      ; --> #t
 (call/cc (lambda (k) (same? '(a (b (c) (d e))) '(a (b (c) (d e))) k)))  ; --> #t
 (call/cc (lambda (k) (same? '(a (b (F) (d e))) '(a (b (c) (d e))) k)))  ; --> #f
 (call/cc (lambda (k) (same? '(a (b)) '(a (b (c) (d))) k)))              ; --> #f

答案 2 :(得分:0)

我也有一个持续的答案。但是现在我有两个延续,一个是真的,一个是假的。如果要分支结果,这非常有用。我还包括'same ?,它隐藏了所有的延续,所以你不必处理它们。

(define (same? a b)
  (call/cc (λ (k) (cont-same? a b (λ () (k #t)) (λ () (k #f))))))

(define (cont-same? a b return-t return-f)
  (define (atest c d)  
    ;; Are they foo?  If they both are, then true
    ;; If they both aren't false
    ;; if they are different, then we are done
    (if (and c d)
        #t
        (if (or c d)
            (return-f)
            #f)))

  (if (atest (null? a) (null? b))  ;; Are they both null, or both not null.
      (return-t)
      (if (atest (pair? a) (pair? b))
          (cont-same? (car a)
                      (car b) 
                      (λ () (cont-same? (cdr a) (cdr b) ;; If the head are the same, compare the tails
                                        return-t return-f)) ;; and if the tails are the same, then the entire thing is the same
                      return-f)          
          (if (equal? a b) ;; Both are atoms
              (return-t)
              (return-f)))))