Sorting a list of lists in Common Lisp

1.9k views Asked by At

I'm trying to write some function to sort this type of list:

((1 A) (2 E) (4 D))

I found the built-in function sort in Common Lisp, but I can't do what I want.
This should be the result:

'((1 A) (4 D) (2 E))

I want to sort the list by the second element of each lists, alphabetically.

This is what I've done:

(sort '((1 A) (4 D) (2 E)) #'char-lessp :key #'second)

Anyway, I would understand how to sort a list with a specific function, using :key'.

Thank you.

1

There are 1 answers

0
Renzo On BEST ANSWER

You should use:

(sort '((1 A) (4 E) (2 D)) #'string<= :key #'second)

The reason is that char-lessp compares characters, and A, E and D are not characters, but symbols. The function string< can used to compare their names, which are the strings "A", "E" and "D". For instance:

CL-USER> (string= 'symbol "SYMBOL")
T
CL-USER> (symbol-name 'symbol)
"SYMBOL"

Note that the comparison operators on strings have two versions, for case sensitive and case insensitive comparisons:

CL-USER> (string= "a" "A")
NIL
CL-USER> (string-equal "a" "A")
T
CL-USER> (string= 'a "a")
NIL
CL-USER> (string-equal 'a "a")
T