简体   繁体   English

在Lisp中对char列表进行排序

[英]Sorting a list of char in Lisp

Is there a way to sort a list made of only characters in alphabetic order (from "a" to "z"), such as: (list cmayk) => (list ackmy)? 有没有一种方法可以对仅由字母组成的列表进行排序(从“ a”到“ z”),例如:(list cmayk)=>(list ackmy)?

I didn't found a sort like that, so i thought this could solve the problem: 我没有找到这样的东西,所以我认为这可以解决问题:

cl-prompt> (setq q (mapcar 'string '(c m a y k))) => ("C" "M" "A" "Y" "K")
cl-prompt> (sort q 'string<) => ("A" "C" "K" "M" "Y")

At this point i'm stuck, because by using the char converter the output will not be the list i want. 在这一点上,我很困惑,因为通过使用char转换器,输出将不是我想要的列表。 Example: 例:

char (string 'a) 0 => #\A

And i will have a list made of: (#\\A #\\C #\\K #\\M #\\Y), which is not the result i want. 我将得到一个列表,其中包括:(#\\ A#\\ C#\\ K#\\ M#\\ Y),这不是我想要的结果。

One can convert characters to their ASCII numbers, sort the numbers and convert back to characters. 可以将字符转换为其ASCII数字,对数字进行排序,然后转换回字符。 Following is code in Racket, a Lisp/Scheme derivative: 以下是Racket中的一个Lisp / Scheme派生代码:

(define l (list #\c #\m #\a #\y #\k))
(map integer->char
     (sort (map char->integer l) <))

Output: 输出:

'(#\a #\c #\k #\m #\y)

In the case of (cmayk) , you have a list of symbols. 对于(cmayk) ,您有一个符号列表。 In the case of (#\\A #\\C #\\K #\\M #\\Y) , you have a list of characters. (#\\A #\\C #\\K #\\M #\\Y) ,您有一个字符列表。

If you want to sort a list of symbols according to the symbol names, you can do (I am assuming the list is bound to the variable foo below): 如果要根据符号名称对符号列表进行排序,可以这样做(我假设该列表绑定到下面的变量foo):

(setq foo (sort foo #'string< :key #'symbol-name))

Note that the :key #'symbol-name could be argued to be superfluous, as string< actually operates on "string designators", but it is much clearer to a human reader that you are indeed intending to sort the list based on symbol names if you say so explicitly. 注意:key #'symbol-name可能被认为是多余的,因为string<实际上是在“字符串指定符”上运行的,但是对于人类读者来说,您确实打算根据符号名对列表进行排序如果你这么明确地说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM