Sorting lists according to some elements

I am new to Lisp and I want to learn Lisp programming. I want to sort some lists read from a text file, for example, 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 whole element or perhaps the second or third, etc.?

I have the following idea:

  • read them all and put them on the list of lists.
  • iterate over the list of containers and compare the values โ€‹โ€‹of the list with the following, as in sorting bubbles.

Are there more suitable data structures to achieve this, maybe like collections in Java that automatically match comparable objects that contain sorting and full sorting?

Many thanks.

+7
source share
2 answers

The standard sort function takes an argument :key , which can be used to retrieve a value from an object for use as a sort key. For example, if you have a list from a file in a list called objects , the following destructively sorts objects first integer element and returns a sorted list:

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

See http://l1sp.org/cl/sort for an exact specification of the Common Lisp sort function.

+10
source
 (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) 
+1
source

All Articles