help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: sorting a list


From: Pascal Bourguignon
Subject: Re: sorting a list
Date: Thu, 17 Apr 2008 20:09:22 +0200
User-agent: Gnus/5.1008 (Gnus v5.10.8) Emacs/22.1 (gnu/linux)

Seweryn Kokot <skokot@o2.pl> writes:

> Assume I have a list
>
> '(("abc" "xxsx") 
>   ("zdfa" "xxsx") 
>   ("dddbc" "xxsx") 
>   ("cabc" "xxsx"))
>
> How to sort the list according to the first element in the lists so to
> get
>
> '(("abc" "xxsx")
>   ("cabc" "xxsx")
>   ("dddbc" "xxsx")
>   ("zdfa" "xxsx"))

(require 'cl)
(sort* list (function string<) :key (function first))

Note that sort and sort* are destructive of the original list.  
You must not give it a literal list.

(defun f-good ()
 (let ((list '(("abc" "xxsx") 
               ("zdfa" "xxsx") 
               ("dddbc" "xxsx") 
               ("cabc" "xxsx"))))
  (list (second list)
        (first (sort* (copy-list list)
                      (function string<) :key (function first))))))

(defun f-bad ()
 (let ((list '(("abc" "xxsx") 
               ("zdfa" "xxsx") 
               ("dddbc" "xxsx") 
               ("cabc" "xxsx"))))
  (list (second list)
        (first (sort* list
                      (function string<) :key (function first))))))

(list (f-good) (f-good))
--> ((#1=("zdfa" "xxsx") #2=("abc" "xxsx")) (#1# #2#))

(list (f-bad) (f-bad))
--> ((("zdfa" "xxsx") #1=("abc" "xxsx")) (("cabc" "xxsx") #1#))


-- 
__Pascal Bourguignon__                     http://www.informatimago.com/

READ THIS BEFORE OPENING PACKAGE: According to certain suggested
versions of the Grand Unified Theory, the primary particles
constituting this product may decay to nothingness within the next
four hundred million years.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]