2011-01-05 87 views
7

我是Lisp的新手,我想學習Lisp編程。 我想在下面的表格列出了一些從一個文本文件中讀取,如排序:根據一些元素排序列表

(a 120 135 124 124) 
(b 120 135 124 124) 
(c 120 135 124 124) 

什麼是根據第一個整數元素或可能第二或第三等對它們進行排序的最好方法?

我有以下想法:

  1. 閱讀它們,並把它們放到列表
  2. 遍歷容器的目錄列表,並與下面的一個像冒泡排序列表中的值進行比較。

是否有更合適的數據結構來實現這一點,也許像Java中的集合,其中包含自動包含排序邏輯和fullfill排序的可比對象?

非常感謝。

回答

10

標準sort函數採用:key參數,該參數可用於從對象中提取值以用作排序關鍵字。對於你的例子,如果你在一個列表中的文件有每個列表稱爲objects,下面的破壞性排序objects第一整數元素,並返回一個排序列表:

(sort objects #'< :key #'second) 

爲常見的精確規範請參閱http://l1sp.org/cl/sort Lisp的sort功能。

1
(defun position-of-first-int (alist) 
    (position (find-if 
      #'(lambda (x) (not (numberp x))) 
      alist) 
      alist)) 

(defun sort-from-first-int (alist) 
    (sort (subseq alist (1+ (position-of-first-int alist))) #'<)) 

測試:

> (setf a '(a 120 135 124 124)) 
> (setf b '(120 b 135 124 124)) 
> (setf c '(120 135 c 124 110)) 

> (format t "~a~%" (sort-from-first-int a)) 
(120 124 124 135) 
> (format t "~a~%" (sort-from-first-int b)) 
(124 124 135) 
> (format t "~a~%" (sort-from-first-int c)) 
(110 124)