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:
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.
sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.
Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable.
sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.
sort() only works for sorting lists. sorted() function is more versatile as we can use it to sort other data types and objects. Today we will see how to sort lists, tuples and dictionaries using the sorted() function.
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.
(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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With