2013-03-19 84 views
2

有沒有辦法只提取列表中的數字? 我正在使用初學者語言包,所以我不能使用過濾器,這是一個無賴。僅提取列表中的數字

(list a 1 2 b d 3 5)=> 1 2 3 5 etc 我想用這個作爲我的幫助函數的一部分,但我無法弄清楚它!

謝謝!

回答

3

理想的情況下這個問題應該用filter高階程序來解決,就像這樣:

(filter number? '(a 1 2 b d 3 5)) 
=> '(1 2 3 5) 

...但是因爲這就像是一門功課,我給你如何解決一些提示通過手頭的問題,只是填寫了空白:

(define (only-numbers lst) 
    (cond (<???>      ; is the list empty? 
     <???>)      ; return the em´pty list 
     (<???>      ; is the 1st element in the list a number? 
     (cons <???>     ; then cons the first element 
       (only-numbers <???>))) ; and advance the recursion 
     (else       ; otherwise 
     (only-numbers <???>))))  ; simply advance the recursion 

注意,這個解決方案遵循衆所周知的模板,各種各樣的配方的遞歸處理列表,進而創建一個新的列表作爲輸出。不要忘了測試你的程序:

(only-numbers '(a 1 2 b d 3 5)) 
=> '(1 2 3 5) 

(only-numbers '(1 2 3 4 5)) 
=> '(1 2 3 5) 

(only-numbers '(a b c d e)) 
=> '() 
+0

downvoter:care to comment? – 2013-03-19 22:05:40