仅提取列表中的数字

问题描述:

有没有办法只提取列表中的数字? 我正在使用初学者语言包,所以我不能使用过滤器,这是一个无赖。仅提取列表中的数字

(list a 1 2 b d 3 5)=> 1 2 3 5 etc 我想用这个作为我的帮助函数的一部分,但我无法弄清楚它!

谢谢!

理想的情况下这个问题应该用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