仅提取列表中的数字

时间:2013-03-19 18:34:04

标签: scheme racket

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

(列出a 1 2 b d 3 5)=> 1 2 3 5等 我想把它作为我帮助函数的一部分,但我无法理解它!

谢谢!

1 个答案:

答案 0 :(得分: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

请注意,此解决方案遵循一个众所周知的模板, recipe ,用于递归处理列表,然后创建新列表作为输出。不要忘记测试你的程序:

(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))
=> '()