我正尝试在这样的函数中进行比较:
(defun omember (x l)
(cond
((null l) nil)
((eq (car l) x) t)
((string< (car l) x) (omember (x (cdr l))))
(t nil)))
它只是遍历列表并搜索列表 l 中的元素是否为 x。这个想法是因为传递的列表是排序的,你不需要在所有列表中搜索一个值。只要你的值(value)大于你可以返回零的元素。但是,“小于”功能不起作用。我为字符串和整数尝试了“string<”和“<”。 另外,我想知道是否有一种机制可以将列表中的整数作为字符串并在字符串中进行比较,因为传入的列表可以是整数也可以是字符串。
最佳答案
如果你想让它以一般方式工作,你应该将比较函数作为参数传递:
(defun member-of-sorted (item list
&key (test #'=) (end-test #'<) (key #'identity))
(loop :for tail :on list
:for element := (funcall key (first tail))
:until (funcall end-test item element)
:when (funcall test item element)
:do (return-from member-of-sorted tail))
nil)
我尽量使它与标准成员
相似。如果你不想在数字上使用它,而是在其他东西上使用它,请传递适当的 :test
和 :end-test
参数。如果您在同一使用位置有不同的类型,您可以围绕它包装一个 typecase 形式。
编辑:我应该添加用法示例:
(member-of-sorted 3 '(1 2 3 4 5 6))
=> (3 4 5 6)
(member-of-sorted 3/2 '(1 2 3 4 5 6))
=> NIL
(member-of-sorted "foo" '("bar" "baz" "foo" "quux")
:test #'string=
:end-test #'string<)
=> ("foo" "quux")
(member-of-sorted #\D '(#\A #\C #\E #\S)
:test #'char=
:end-test #'char<)
=> NIL
(member-of-sorted #\D '(#\A #\C #\D #\E #\S)
:test #'char=
:end-test #'char<)
=> (#\D #\E #\S)
关于string - 口齿不清比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13190783/