对Lisp中的char列表进行排序(Sorting a list of char in Lisp)

编程入门 行业动态 更新时间:2024-10-10 05:24:49
对Lisp中的char列表进行排序(Sorting a list of char in Lisp)

有没有一种方法可以按字母顺序(从“a”到“z”)排序仅由字符组成的列表,如:(list cmayk)=>(list ackmy)?

我没有找到这样的排序,所以我认为这可以解决问题:

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")

在这一点上我卡住了,因为通过使用char转换器输出将不会是我想要的列表。 例:

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

我将有一个列表:(#\ A#\ C#\ K#\ M#\ Y),这不是我想要的结果。

Is there a way to sort a list made of only characters in alphabetic order (from "a" to "z"), such as: (list c m a y k) => (list a c k m y)?

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. 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.

最满意答案

在(cmayk)的情况下,你有一个符号列表。 在(#\A #\C #\K #\M #\Y) ,您有一个字符列表。

如果你想根据符号名称对符号列表进行排序,你可以这样做(我假设列表绑定到下面的变量foo):

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

请注意:key #'symbol-name可能被认为是多余的,因为string<实际上是在“字符串指示符”上操作的,但是对于读者来说,您确实打算基于符号名称对列表进行排序如果你明确地这样说。

In the case of (c m a y k), you have a list of symbols. In the case of (#\A #\C #\K #\M #\Y), you have a list of characters.

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):

(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.

更多推荐

本文发布于:2023-07-30 15:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338768.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   char   Lisp   Sorting   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!