1

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 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.