Question: Sorting a list of lists in Common Lisp

Question

Sorting a list of lists in Common Lisp

Answers 1
Added at 2016-12-17 17:12
Tags
Question

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.

Answers to

Sorting a list of lists in Common Lisp

nr: #1 dodano: 2016-12-17 17:12

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
Source Show
◀ Wstecz