如何在Common Lisp中按特定顺序对列表进行排序?

时间:2015-12-11 12:07:13

标签: sorting lisp common-lisp

所以我知道如何对像(1 2 3)这样的列表进行排序 例如,在Common Lisp中按升序排列。

但我需要按照 3rd 元素的降序对此列表进行排序:( (1 2 3) nil 1)

有办法吗?

1 个答案:

答案 0 :(得分:2)

sort函数接受一个谓词,该谓词将用于判断元素何时位于另一个元素之前(参见hyperspec)。

因此,定义一个函数compare-3rd

(defun compare-3rd (a b)
  (< (nth 2 a) (nth 2 b)))

并将其用作谓词:

(sort '(( (1 2 3) nil 4)
    ( (1 2 3) nil 2)
    ( (1 2 3) nil 3))
      'compare-3rd)

==> (((1 2 3) NIL 2) ((1 2 3) NIL 3) ((1 2 3) NIL 4))

当然,如果您想降序,可以在>中使用<代替compare-3rd

相关问题