Common- Lisp: how to sort string characters?

I know how to do this in all the other languages ​​that I know, but I'm just starting Lisp and not really getting it. My idea

  • make a list of characters
  • convert to ascii values
  • kind
  • convert back to characters
  • convert back to string

Seems harsh. Is there a better way to do this? I am trying to write a function that, given a string, returns a string with sorted letters. So for example:

gate => aegt house => ehosu door => door 

This procedure will be used as part of the anagram finder.

Thanks!

+4
source share
3 answers

In Common Lisp, strings are sequences, and sort works with any type of sequence, so it will do the trick.

Here is an example:

 (let ((the-string (copy-seq "this is the string"))) (sort the-string #'char-lessp)) ;; => " eghhiiinrsssttt" 

And here is the Hyperspec entry for sort and stable-sort . Just select your predicate (second sort argument) to get your desired sort order.

Note that I used copy-seq in the example because sort is destructive - it changed the string in place.

+10
source

The sort function takes a sequence that already exists, so your only problem is finding the right comparison function. Characters are not numbers, so you should use character comparison functions, for example. char> :

 * (sort (copy-seq "hello") #'char>) "ollhe" 
+6
source

A string is a sequence of characters. sort sorts sequences to sort a string similar to sorting a list:

 (setq tester (copy-seq "lkjashd")) => "lkjashd" (stable-sort tester #'char-lessp) => "adhjkls" tester => "adhjkls" ; NB: it mutates the string! 
+2
source

Source: https://habr.com/ru/post/1497591/


All Articles