如何检查列表中的所有元素是否相等? [英] How do I check if all elements in a list are equal?

查看:114
本文介绍了如何检查列表中的所有元素是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止所得到的,但这只是比较第一个元素和第二个元素。因此,如果我评估此?(check'(aaaa)),则应返回true;但如果我评估?(check'(aaaa)),则应返回Nil

This is what I got so far, but it is only comparing the first element with the second element. So if I evaluate this ?(check ‘(a a a a)) it should return true but if I evaluate ?(check ‘(a a a b)) it should return Nil

(defun check (lista)
(cond
((null lista)'())
((equal (car lista)(cadr lista))cdr lista)
(t(check (cdr lista)))))


推荐答案

一些说明:


  • 缩进代码以提高可读性

  • 检查大小写其中列表仅包含一个元素

  • 当第一个元素和第二个元素不同时,您可以递归调用函数,但是在这种情况下,您不需要它,因为已知该属性为false

您的尝试几乎是好的,您只将递归调用放在错误的位置。相等是可传递的,因此您只需要比较每个元素及其后继元素,并查看该属性是否适合子列表。我会这样写:

Your attempt is almost good you only put the recursive call in a wrong place. Equality is transitive so you only need to compare each element with its successor and see if the property holds for the sublist. I would personally write it as follow :

(defun all-equal-p (list)
  (or (null (rest list)) ;; singleton/empty
      (and (equalp (first list)
                   (second list))
           (all-equal-p (rest list)))))

这篇关于如何检查列表中的所有元素是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆