Lisp HUG Maillist Archive

sort lists

Hi,

I am trying to sort lists but can't find any help to do deeper sort.

Example:

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

(stable-sort list #'< :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))

but I am looking for:
--> ((0) (0) (0 0 3 0) (0 1 3) (0 1 5) (0 1 5) (0 3 0) (1) (1) (2) (2 7 19))

any solution or hint.

Thanks,
--
Janusz Podrazik
MRAC Publishing

Re: sort lists

You'll need to write a custom test to provide the sort order you want. just using #'< and the car sorts on the first element but does not specify what to do when the first elements of two items are equal. You'd want something like 

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

(defun my-test< (l1 l2)
  (loop for item1 in l1 for item2 in l2 do
       (cond ((null item1) (return nil))
	     ((null item2) (return t))
	     ((< item1 item2) (return t))
	     ((> item2 item2) (return nil)))))

(stable-sort list #'my-test<)
==> ((0) (0 3 0) (0 1 3) (0 1 5) (0 1 5) (0) (0 0 3 0) (1) (1) (2) (2 7 19))

On May 14, 2011, at 10:20 AM, Janusz Podrazik wrote:

> 
> Hi,
> 
> I am trying to sort lists but can't find any help to do deeper sort.
> 
> Example:
> 
> (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)))
> 
> (stable-sort list #'< :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))
> 
> but I am looking for:
> --> ((0) (0) (0 0 3 0) (0 1 3) (0 1 5) (0 1 5) (0 3 0) (1) (1) (2) (2 7 19))
> 
> any solution or hint.
> 
> Thanks,
> --
> Janusz Podrazik
> MRAC Publishing

--
Gary Warren King, metabang.com 
Cell: (413) 559 8738
Fax: (206) 338-4052
gwkkwg on Skype * garethsan on AIM * gwking on twitter


Re: sort lists

On 5/15/11, Gary King <gwking@metabang.com> wrote:
>
> You'll need to write a custom test to provide the sort order you want. just
> using #'< and the car sorts on the first element but does not specify what
> to do when the first elements of two items are equal. You'd want something
> like
>
> (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)))
>

Also, don't forget to make copies (probably copy-tree in your case) to
avoid destructive operations (from sort/stable-sort) on quoted literal
values.

Yong.


Updated at: 2020-12-10 08:37 UTC