方案:我不知道实现给定的功能 [英] Scheme : I have no idea to implement given function

查看:39
本文介绍了方案:我不知道实现给定的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是编程语言语用学,迈克尔·斯科特"的练习.

It's the exercise of "Programming language pragmatics, Michael Scott" .

问.返回包含满足给定谓词的给定列表的所有元素的列表.例如, (filter (lambda (x) (< x 5) '(3 9 5 8 2 4 7)) 应该返回 (3 2 4).

Q. return a list containing all elements of a given list that satisfy a given predicate. For example, (filter (lambda (x) (< x 5) '(3 9 5 8 2 4 7)) should return (3 2 4).

我认为这个问题不仅需要满足上述所有谓词的函数.但我没有任何想法来实现这样的功能.请帮忙.

I think that question require function which satisfy every predicate not only above. But I don't have any idea to implement such function. Please help.

推荐答案

filter 过程已经存在于大多数 Scheme 实现中,它的行为符合预期:

(filter (lambda (x) (< x 5)) '(3 9 5 8 2 4 7))
=> '(3 2 4)

现在,如果问题是如何实现它,那就很简单了——我会给你一些提示,这样你就可以自己编写了.这里的技巧是注意到该过程正在接收另一个过程作为参数,一个谓词,它会返回 #t#f> 当应用于输入列表中的每个元素时.那些评估为 #t 的被保留在输出列表中,那些评估为 #f 的被丢弃.这是解决方案的框架,请填空:

Now, if the question is how to implement it, it's rather simple - I'll give you some hints so you can write it by yourself. The trick here is noticing that the procedure is receiving another procedure as parameter, a predicate in the sense that it'll return #t or #f when applied to each of the elements in the input list. Those that evaluate to #t are kept in the output list, those that evaluate to #f are discarded. Here's the skeleton of the solution, fill-in the blanks:

(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 recursion

这篇关于方案:我不知道实现给定的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆