这是“编程语言语用学,Michael Scott”的练习。
返回一个包含给定列表中满足给定谓词的所有元素的列表。例如,(filter (lambda (x) (< x5) '(3 9 5 8 2 4 7)应该返回(3 2 4)。
我认为这个问题需要满足每个谓词的函数,而不仅仅是上面的。但是我没有任何想法来实现这样的功能。请帮帮忙。
发布于 2013-04-08 08:11:37
filter过程已经存在于大多数方案实现中,它的行为符合预期:
(filter (lambda (x) (< x 5)) '(3 9 5 8 2 4 7))
=> '(3 2 4)现在,如果问题是如何实现它,那就相当简单了--我会给你一些提示,这样你就可以自己写了。这里的技巧是注意到该过程正在接收另一个过程作为参数,这是一个谓词,当应用于输入列表中的每个元素时,它将返回#t或#f。求值为#t的值保留在输出列表中,求值为#f的值将被丢弃。下面是解决方案的框架,填入空白处:
(define (filter pred? lst)
(cond (<???> ; if the list is empty
<???>) ; return the empty list
(<???> ; apply pred? on the first element, if it's #t
(cons <???> ; then cons the first element
(filter pred? <???>))) ; and advance recursion
(else (filter pred? <???>)))) ; else just advance recursionhttps://stackoverflow.com/questions/15869018
复制相似问题