Search code examples
lispcommon-lisp

Order Lists by CAR


I need to be able to compare two cars of a list to sort them im LISP.

Lists '(e d) (a b)

I want to compare the cars (e and a). This works using eql. If they don't match, I want to order the lists alphabetically, so (a b) (e d). I'm missing the part where I can see which character is 'bigger', so the check if e or a should come first. I've tried converting them to ascii codes, but that doesn't work for (car a). Using arithmetic operators such as '<' and '>' also doesn't work. Does anyone have an idea on how to do this?


Solution

  • Use string> without symbol-name:

    CL-USER 6 > (string> 'a 'b)
    NIL
    
    CL-USER 7 > (string< 'a 'b)
    0
    

    For the sake of completeness, here is how you should use it inside sort to achieve desired result (sort is destructive- modifies used sequence, so I also used copy-tree to avoid that effect):

    (let ((data '((e d) (a b))))
      (sort (copy-tree data)
            (lambda (x y) (string< (car x) (car y)))))
    
    ((A B) (E D))