如何查看列表是否在普通 lisp 中排序?

Obi*_*obe 2 lisp

如何确定列表是否在普通 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)))
Run Code Online (Sandbox Code Playgroud)

Sva*_*nte 5

您想遍历列表并在每一步检查当前元素是否不大于下一个元素。如果是,您可以跳过其余部分并返回 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
Run Code Online (Sandbox Code Playgroud)

你可以更简洁地做到这一点every

(defun sortedp (list)
  (every #'<= list (rest list)))
Run Code Online (Sandbox Code Playgroud)