Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

sorting lists according to some elements

I am a newbie in Lisp and I want to learn Lisp programming. I want to sort some lists read from a text file, like in the following form:

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

What is the best way to sort them according to the first integer element or maybe second or third and so on?

I have the following idea:

  1. read them all and put them into a list of lists
  2. iterate over the container list and compare the values of list with following one like in bubble sort.

Are there more suitable data structures to achieve this, maybe like Collections in Java which take comparable objects that contain sort logic and fullfill sorting automatically?

Thank you very much.

Upvotes: 7

Views: 3016

Answers (2)

Vijay Mathew
Vijay Mathew

Reputation: 27174

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

Test:

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

Upvotes: 1

Xach
Xach

Reputation: 11854

The standard sort function takes a :key argument that can be used to extract a value from the object to use as the sort key. For your example, if you had each list from the file in a list called objects, the following would destructively sort objects by the first integer element and return a sorted list:

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

See http://l1sp.org/cl/sort for the precise specification of Common Lisp's sort function.

Upvotes: 10

Related Questions