有没有办法只提取列表中的数字? 我正在使用初学者语言包,因此我无法使用过滤器,这很糟糕。
(列出 a 1 2 b d 3 5) => 1 2 3 5 等 我想用它作为我的辅助函数的一部分,但我无法弄清楚!
谢谢!
最佳答案
理想情况下,这个问题应该使用 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))
=> '()
关于scheme - 仅提取列表中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507732/