by lispm · 16y ago · 0 comments
CL-USER 58 > (take '(a b c d) 2)
(A B)
CL-USER 59 > (take '(a b c d) -2)
(C D)
CL-USER 60 > (take '(a b c d) '(0 3))
(A B C)
CL-USER 61 > (take '(a b c d) '(0 -1 2))
(A C)
CL-USER 62 > (take '((a b c d) (1 2 3 4) (5 6 7 8)) 2 2)
((A B) (1 2))
That was easy. (defun take-1 (it what)
(cond ((eq what :all) it)
((eq what :none) nil)
((and (numberp what) (plusp what))
(subseq it 0 what))
((and (numberp what) (minusp what))
(last it (- what)))
((and (consp what)
(= (length what) 1)
(numberp (first what)))
(nth (first what) it))
((and (consp what)
(= (length what) 2)
(numberp (first what))
(numberp (second what)))
(let ((end (if (minusp (second what))
(+ (length it) (second what))
(second what))))
(subseq it (first what) end)))
((and (consp what)
(= (length what) 3)
(numberp (first what))
(numberp (second what))
(numberp (third what)))
(let ((end (if (minusp (second what))
(+ (length it) (second what))
(second what))))
(loop for e = (subseq it (first what)) then (nthcdr (third what) it)
for i from (first what) below end by (third what)
collect (first e))))))
(defun take (thing &rest description)
(cond ((null description) nil)
((and (consp description)
(= (length description) 1))
(take-1 thing (first description)))
(t (loop for e in (take-1 thing (first description))
collect (apply #'take e (rest description))))))