I am trying to develop a function which does as mentioned in the subject line i.e adding an element to a list while maintaining the sort order. The following is what I have managed:
- Code: Select all
(defun sort-push(lst n &key (test #'<) (key #'identity))
(labels ((rec (lst n acc)
(if (null lst)
(reverse (cons n acc))
(if (funcall test (funcall key n) (funcall key (car lst)))
(append (reverse (cons n acc)) lst)
(rec (cdr lst) n (cons (car lst) acc))))))
(rec lst n ())))
(sort-push '((1 . 2) (5 . 6)) (3 . 4) :key #'cdr)
((1 . 2) (3 . 4) (5 . 6))
This function is resulting into what is being expected. However, it appears something isn't right about it. Can you point out the drawbacks of this function? Its taking a long time to push an element into a huge list of cons. Also, please point out if this functionality has been already implemented into the current list implementations.
Regards,
ykm.