2014-02-15 194 views
0
(defun filter-numbers-rec (inlist) 
    "This function filters out non-numbers from its input list and returns 
the result, a list of numbers" 
    (cond 
    ((not (listp inlist)) 
    (princ "Argument must be a list") 
    (terpri) 
    ()) 
    ((null inlist) 
    ()) 
    ((not (numberp (car inlist))) 
    (filter-numbers-rec (cdr inlist))) 
    (t 
    (cons (car inlist) 
      (filter-numbers-rec (cdr inlist)))))) 

回答

3

好,功能所做的說明是要從列表中刪除每一件事情如果不是一些,所以一個很好的候選人這裏是remove-if-not,你會使用方法如下:

(remove-if-not 'numberp '(1 a 2 b 3 C#\x (y 4))) 
;=> (1 2 3) 

如果由於某種原因,你想要的方式,(可能)不使用遞歸,你可以用它來寫這個do

(do ((list '(1 a 2 b 3 C#\x (y 4)) (rest list)) 
    (result '())) 
    ((endp list) (nreverse result)) 
    (when (numberp (car list)) 
    (push (car list) result))) 
;=> (1 2 3) 

如果你不喜歡的do的贅言,你可以使用loop

(loop :for x :in '(1 a 2 b 3 C#\x (y 4)) 
    :when (numberp x) 
    :collect x) 
;=> (1 2 3)