【问题标题】:Scheme - checking structural equivalences of lists (how to use AND)Scheme - 检查列表的结构等价性(如何使用 AND)
【发布时间】:2014-11-13 22:14:27
【问题描述】:

我正在尝试编写一个程序来检查某些列表输入的结构等价性,无论它是否包括原子或嵌套子列表。

我在使用 AND 时遇到问题,我什至不知道它是否可行,而且我似乎无法理解我正在查看的文档。

我的代码:

 (define (structEqual a b)
   (cond
     (((null? car a) AND (null? car b)) (structEqual (cdr a) (cdr b)))
     (((null? car a) OR (null? car b)) #f)
     (((pair? car a) AND (pair? car b)) 
      (if (= (length car a) (length car b))
          (structEqual (cdr a) (cdr b))
          #f))
     (((pair? car a) OR (pair? car b)) #f)
     (else (structEqual (cdr a) (cdr b)))))

想法是(我认为):(当我说两者时,我的意思是a或b的当前cdr)

  1. 检查a和b是否都为null,那么它们在结构上是相等的

  2. 检查是否只有 a 或 b 为 null,则它们在结构上不相等

  3. 检查两者是否成对

  4. 如果它们都是对,则查看对的长度是否相等,如果不是,它们在结构上不相等。

  5. 如果它们不是两个对,那么如果其中一个是一对而另一个不是,那么它们在结构上是不等价的。

  6. 如果它们都不是对,那么它们都必须是原子,所以它们在结构上是等价的。

如您所见,我试图通过检查 a 或 b 的汽车的等价性来递归地执行此操作,然后如果它们失败则返回 #f 或者如果它们在每个上都等价则转到每个的 cdr步。

有什么帮助吗?

【问题讨论】:

  • 格式应该是(和 expr1 expr2...)
  • 这也适用于 OR 吗?我假设他们只是返回一个布尔值?

标签: scheme


【解决方案1】:

Scheme(或任何 LISP)中没有中缀运算符,只有前缀。每次操作员都是第一位的。 (or x (and y z q) (and y w e)) 其中每个字母都可以是一个复杂的表达式。不是#f 的所有内容都是真实值。因此(if 4 'a 'b) 的计算结果为a,因为 4 是一个真值。 car 需要括号。

在评估cond 中的另一个谓词时,您应该利用到这一切都是错误的事实。例如。

(define (structure-equal? a b)
  (cond
    ((null? a) (null? b))                                ; if a is null the result is if b is null
    ((not (pair? a)) (not (pair? b)))                    ; if a is not pair the result is if b is not also
    ((pair? b) (and (structure-equal? (car a) (car b))   ; if b is pair (both a and b is pair then) both 
                    (structure-equal? (cdr a) (cdr b)))) ; car and cdr needs to be structurally equal
    (else #f)))                                          ; one pair the other not makes it #f

(structure-equal '(a (b (c d e) f) g . h) '(h (g (f e d) c) b . a)) ; ==> #t

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多