Emacs-Lisp的自然顺序排序

Emacs-Lisp的自然顺序排序,emacs,elisp,natural-sort,Emacs,Elisp,Natural Sort,有人在Emacs Lisp中实现了自然顺序排序吗?我知道写作并不难,但借用别人的作品更容易 (是的,我简直不敢相信我刚刚搜索了一个Emacs函数却找不到它。)这段代码提供了一个可用于排序算法的'dictionary-lessp。到目前为止,似乎在我的测试中起作用: (defun dictionary-lessp (str1 str2) "return t if STR1 is < STR2 when doing a dictionary compare (splitting the s

有人在Emacs Lisp中实现了自然顺序排序吗?我知道写作并不难,但借用别人的作品更容易


(是的,我简直不敢相信我刚刚搜索了一个Emacs函数却找不到它。)

这段代码提供了一个可用于排序算法的
'dictionary-lessp
。到目前为止,似乎在我的测试中起作用:

(defun dictionary-lessp (str1 str2)
  "return t if STR1 is < STR2 when doing a dictionary compare
(splitting the string at numbers and doing numeric compare with them)"
  (let ((str1-components (dict-split str1))
        (str2-components (dict-split str2)))
    (dict-lessp str1-components str2-components)))

(defun dict-lessp (slist1 slist2)
  "compare the two lists of strings & numbers"
  (cond ((null slist1)
         (not (null slist2)))
        ((null slist2)
         nil)
        ((and (numberp (car slist1))
              (stringp (car slist2)))
         t)
        ((and (numberp (car slist2))
              (stringp (car slist1)))
         nil)
        ((and (numberp (car slist1))
              (numberp (car slist2)))
         (or (< (car slist1) (car slist2))
             (and (= (car slist1) (car slist2))
                  (dict-lessp (cdr slist1) (cdr slist2)))))
        (t
         (or (string-lessp (car slist1) (car slist2))
             (and (string-equal (car slist1) (car slist2))
                  (dict-lessp (cdr slist1) (cdr slist2)))))))

(defun dict-split (str)
  "split a string into a list of number and non-number components"
  (save-match-data 
    (let ((res nil))
      (while (and str (not (string-equal "" str)))
        (let ((p (string-match "[0-9]*\\.?[0-9]+" str)))
          (cond ((null p)
                 (setq res (cons str res))
                 (setq str nil))
                ((= p 0)
                 (setq res (cons (string-to-number (match-string 0 str)) res))
                 (setq str (substring str (match-end 0))))
                (t
                 (setq res (cons (substring str 0 (match-beginning 0)) res))
                 (setq str (substring str (match-beginning 0)))))))
      (reverse res))))
示例用法是:

(sort '("b" "a" "1" "f19" "f" "f2" "f1can") 'dictionary-lessp)
屈服

("1" "a" "b" "f" "f1can" "f2" "f19")

这太棒了,谢谢!另外,我想你忘了一个;;在“p!=0”之前。我不明白注释,你在说哪一个检查?文本“p!=0”看起来像一个注释(在这里没有任何意义),但它前面没有注释标记。
("1" "a" "b" "f" "f1can" "f2" "f19")