我在LISP中有清单:
((1 b) (1 a) (2 D) (1 z) (1 t) (2 a) (3 n))
我必须先按数字对其进行排序,如果按字符的字法顺序相等,则输出应为:
((1 a) (1 b) (1 t) (1 z) (2 a) (2 d) (3 n))
我试图对一个参数进行排序,然后对另一个参数进行排序,我该如何对这两个函数进行组合?
;;(sort '((1 b) (1 a) (2 D) (1 z) (1 t) (2 a) (3 n)) #'< :key #'car )
;;(sort '((1 b) (1 a) (2 D) (1 z) (1 t) (2 a) (3 n)) #'string< :key #'second )
有更简单的方法吗?
谢谢
正如coredump所说,既然您确实需要列表比较功能,那么一种不错的方法是做meta事情:不要编写一个,而是编写一个使比较列表的功能的函数。这是一个这样的功能:
(defun make-list-comparator (&rest predicates)
(labels ((tails< (l1t l2t pt)
(let ((< (first pt))
(e1 (first l1t))
(e2 (first l2t)))
(cond
((funcall < e1 e2) t)
((funcall < e2 e1) nil)
((and (null l1t) (null l2t) (null pt)) nil)
((or (null l1t) (null l2t) (null pt))
(error "crashed into the end"))
(t (tails< (rest l1t) (rest l2t) (rest pt)))))))
(lambda (l1 l2)
(tails< l1 l2 predicates))))
现在
> (sort (copy-list '((1 b) (1 a) (2 D) (1 z) (1 t) (2 a) (1)))
(make-list-comparator
#'<
(lambda (s1 s2)
(string< (string s1) (string s2)))))
((1 a) (1 b) (1 t) (1 z) (2 a) (2 d) (3 n))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句