ALL NICE !
(defun f (L n)
(if (> n (car l)) (cons n l)
(cons (car l) (f (cdr l) n))))
Test
(f '(6 5 4 3 2) 1) ; (6 5 4 3 2 1)
(f '(9 8 7 6 5 3) 1) ; (9 8 7 6 5 3 1)
(f '(9 8 7 6 5 3) 10) ; (10 9 8 7 6 5 3)
(f '(9 8 7 6 5 3) 3) ; (9 8 7 6 5 3 3)
(f '(9 8 7 6 5 3) 5) ; (9 8 7 6 5 5 3)
(f '(9 8 7 6 5 3) 4) ; (9 8 7 6 5 4 3)
(f '(9 8 7 6 5 3) 9) ; (9 9 8 7 6 5 3)
Not exactly what the OP asked for. He wanted the list to stay the same length by dropping the smallest value after inserting the new value.
Strangely enough, the reverse function doesn't seem to be all that slow. I've just tried re-imlpementing my
ButLastN function by using the same principle as my previous post.
(defun butlastN1
(lst n
/ m
)
But it seems to actually run slower than the old one which reversed the list twice:
_$ (QuickBench '((ButLastN lst 100) (ButLastN1 lst 100)))
Benchmarking .. done for 4096 iterations. Sorted from fastest.
Statement Increment Time(ms) Normalize Relative
--------------------------------------------------------------------------------
(BUTLASTN LST 100) 4096 1950 1950 5.51
(BUTLASTN1 LST 100) 512 1342 10736 1.00
--------------------------------------------------------------------------------
_$ (QuickBench '((ButLastN lst 500) (ButLastN1 lst 500)))
Benchmarking .. done for 2048 iterations. Sorted from fastest.
Statement Increment Time(ms) Normalize Relative
--------------------------------------------------------------------------------
(BUTLASTN LST 500) 2048 1498 1498 2.96
(BUTLASTN1 LST 500) 512 1107 4428 1.00
--------------------------------------------------------------------------------
_$ (QuickBench '((ButLastN lst 900) (ButLastN1 lst 900)))
Benchmarking .. done for 1024 iterations. Sorted from fastest.
Statement Increment Time(ms) Normalize Relative
--------------------------------------------------------------------------------
(BUTLASTN LST 900) 1024 1044 1044 1.66
(BUTLASTN1 LST 900) 1024 1732 1732 1.00
--------------------------------------------------------------------------------
_$ (QuickBench '((ButLastN lst 950) (ButLastN1 lst 950)))
Benchmarking .. done for 1024 iterations. Sorted from fastest.
Statement Increment Time(ms) Normalize Relative
--------------------------------------------------------------------------------
(BUTLASTN LST 950) 1024 1060 1060 1.59
(BUTLASTN1 LST 950) 1024 1685 1685 1.00
--------------------------------------------------------------------------------
_$ (QuickBench '((ButLastN lst 990) (ButLastN1 lst 990)))
Benchmarking .. done for 1024 iterations. Sorted from fastest.
Statement Increment Time(ms) Normalize Relative
--------------------------------------------------------------------------------
(BUTLASTN LST 990) 1024 1107 1107 1.47
(BUTLASTN1 LST 990) 1024 1622 1622 1.00
--------------------------------------------------------------------------------
Run on a sample list of 1000 integers.