【问题标题】:How to see if a list is sorted in common lisp?如何查看列表是否以 common lisp 排序?
【发布时间】:2016-03-17 18:46:57
【问题描述】:

在 common lisp 中如何确定列表是否按升序排序?我在正确的轨道上吗?

(defun is-sorted (lst)
  (cond
    ((null lst ) T) 
    ((<= car lst (lst cdr lst)))
    ((is-sorted (cdr lst) nil))))

(print (is-sorted '(1 2 3 4 5 6 7)))

【问题讨论】:

  • 你应该在这里发布你的代码而不是链接。
  • 我无法正确格式化它。
  • 您需要在每行前面有四个空格才能将其格式化为代码。还有一个按钮(带花括号的那个)

标签: lisp


【解决方案1】:

您想遍历列表并在每一步检查当前元素是否不大于下一个元素。如果是,您可以跳过其余部分并返回 false。如果到达终点,则返回 true。

(defun sortedp (list)
  (cond ((endp (rest list)) t)  ; end of the list: success
        ((> (first list) (second list)) nil)  ; first two not sorted: fail
        (t (sortedp (rest list)))))  ; go to next two

您可以使用every 更简洁地做到这一点:

(defun sortedp (list)
  (every #'<= list (rest list)))

【讨论】:

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