0

Q: how can I get string-collate-lessp to sort correctly?

string-collate-lessp is supposed to sort two strings in collation order:

Return t if first arg string is less than second in collation order. Symbols are also allowed; their print names are used instead.

This function obeys the conventions for collation order in your locale settings....

Yet I'm getting odd behavior with it. This works:

(string-collate-lessp "abcdef" "abcdefg") ; => t

As does this:

(string-collate-lessp "abcdef" "abcaef")  ; => nil (note "a" in place of "d")

And yet this does not:

(string-collate-lessp "abcdef" "abc aef") ; => nil (note "space a")

While this does work:

(string-collate-lessp "abcdef" "abc eef") ; => t (note "space e")

It seems to be the case that the function is ignoring the space between the two "words" in the second string and using the first letter of the second word to compare to the corresponding letter in the first word (here, the fourth letter).

This behavior leads to strange outcomes. For example, when I want to alphabetize these two names, it puts them in the incorrect order:

(string-collate-lessp "Baumgartner, Robert"
                      "Baum, Matthew")  ; => t

Yet "Baum" should come before "Baumgartner" in English-language sorting, not after. If it were "Baum, Arthur", however, it sorts correctly, because the "a" in "Arthur" sorts before the "g" in "Baumgartner":

(string-collate-lessp "Baumgartner, Robert"
                      "Baum, Arthur")  ; => nil

How do I fix this problem?

NB: I am not using plain string-lessp because some of the strings have diacritics in them. See this related post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.