2016-08-20 4 views
0

나는 모든 것을 둘러 보았지만 간단한 답을 찾지 못했습니다.단계별로 목록 조각 내기

loop에 의하지 않고 Common Lisp에서 목록을 특정 step으로 슬라이스하려면 어떻게해야합니까? subseq은 세 번째 매개 변수, 즉 (subseq lst start end step)을 사용하지 않습니다.

파이썬 상당 :

lst[start:end:step] 

답변

4

표준 CL 비슷한 아무것도 없다. 이를 구현하려면 REDUCE 또는 DO을 사용할 수 있습니다. 난 그냥 LOOP을 사용합니다 :

도우미 기능 :

(defun %take (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 ((start (first what)) 
       (end (if (minusp (second what)) 
         (+ (length it) (second what)) 
         (second what))) 
       (by-step (third what))) 
      (loop for e = (subseq it start) then (nthcdr by-step e) 
       for i from start below end by by-step 
       collect (first e)))))) 

TAKE :

(defun take (thing &rest description) 
    "Taking things from lists like in Mathematica 
Description is one or more of: 
    :all | :none | [sign]number | (start [end [step]])" 
    (cond ((null description) nil) 
     ((and (consp description) 
       (= (length description) 1)) 
     (%take thing (first description))) 
     (t (loop for e in (%take thing (first description)) 
       collect (apply #'take e (rest description)))))) 

예 :

CL-USER 27 > (take '(0 1 2 3 4 5 6 7 8 9 10 11) '(2 7 2)) 
(2 4 6) 

CL-USER 28 > (defun sublist (list start end step) 
       (take list (list start end step))) 
SUBLIST 

CL-USER 29 > (sublist '(0 1 2 3 4 5 6 7 8 9 10 11) 2 7 2) 
(2 4 6) 
관련 문제