开发者

How to sort a list with sublists (common Lisp)

How to sort a list with sublists?

(setq list '((0) (1) (2) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (1) 
             (2 7 19) (0 0 3 0)))

; restricting the sort to only the first element:

(sort (copy-seq list) #'开发者_如何学C< :key #'car)

--> ((0) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (0 0 3 0) (1) (1) (2) (2 7 19))

The output I am looking for is sort on all elements of the sublist:

--> ((0) (0) (0 0 3 0) (0 1 3) (0 1 5) (0 1 5) (0 3 0) (1) (1) (2) (2 7 19))


Start by defining a function that determines whether one list is less than another. The following example assumes that the lists can only contain numbers:

(defun list< (a b)
  (cond ((null a) (not (null b)))
        ((null b) nil)
        ((= (first a) (first b)) (list< (rest a) (rest b)))
        (t (< (first a) (first b))) ))

Armed with this function, you can now sort the list of lists.

(sort (copy-seq list) #'list<)


To sort on all elements of a sublist, use a custom function for the sort predicate or key. Change the sort predicate to a custom function that can determine the order of two sublists. Alternatively, change the sort key to a custom function that reduces the sublist to a sortable value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜