方案:比较列表大小

发布于 2024-11-01 23:38:21 字数 442 浏览 1 评论 0原文

我的计划程序有问题。我试图获取 2 个列表并比较它们的大小,如果大小相等则返回 true,如果不相等则返回 false。每个原子的值并不重要。

示例:

(structeq '(a (b(c))) '(1(2(3)))) => #t
(structeq '(x) '(()) => #f

这是我的代码:

(define (structeq list1 list2)
    (cond ((null? list1) list2)
    (eq? (length list1) (length list2))))

(structeq '(a b c d) '(a b c))

但是,这会返回最后一个列表的大小。我哪里出错了?

编辑:取消这个问题。我想通了,我只需要删除 cond 语句即可。

I am having an issue with my Scheme program. I am trying to take in 2 lists and compare their sizes and return true is the sizes are equal, and false if they are not. The value of each atom doesn't matter.

Example:

(structeq '(a (b(c))) '(1(2(3)))) => #t
(structeq '(x) '(()) => #f

Here is my code:

(define (structeq list1 list2)
    (cond ((null? list1) list2)
    (eq? (length list1) (length list2))))

(structeq '(a b c d) '(a b c))

However, this returns the size of the last list. Where am I going wrong?

EDIT: Cancel this question. I figured it out, i just needed to remove the cond statement.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦太阳 2024-11-08 23:38:21

请注意:

(define (same-length a b)
  (if (and (null? a) (null? b)) #t
      (if (or (null? a) (null? b)) #f
          (same-length (cdr a) (cdr b)))))

一旦找到较短列表的末尾就会停止。

note that:

(define (same-length a b)
  (if (and (null? a) (null? b)) #t
      (if (or (null? a) (null? b)) #f
          (same-length (cdr a) (cdr b)))))

would stop as soon as it found the end of the shorter list.

深海夜未眠 2024-11-08 23:38:21
(eq? (length list1) (length list2)))) 

代码中的这一行有一个谓词,但没有结果。如果它们相等,您想返回#t。
当列表的长度不相等时,添加一个 else 情况来捕获也是很好的。例如:(else #f)

此处了解有关条件的更多信息。

(eq? (length list1) (length list2)))) 

This line in your code has a predicate but no consequent. If they are equal, you want to return #t.
Also would be good to add an else case to catch when the lists' length are not equal. eg: (else #f)

Read more about conditionals here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文