string - 口齿不清比较

标签 string comparison lisp int

我正尝试在这样的函数中进行比较:

(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/

相关文章:

.net - 如何在 .NET 中创建特定于域的字符串类?

c - 编写一个程序来检查给定的输入字符串是否有平衡括号

linux - 如何在 shell 脚本中比较两个浮点值

java - 如何根据这些条件对对象的 HashSet 进行排序?

java - 在 Java Runtime.getRuntime().exec(...) 中使用引号和双引号

C++仅从数组中获取数据的中间部分

java - 运算符 "+": is it really overloaded for strings?

c++ - C++编译器如何解释字符串/字符中的比较逻辑?

scheme - 以列表形式保存子列表

opengl - 在 FreeBSD 上安装 lisp/opengl