在Scheme中查找列表中的元素
我是计划的初学者,并试图弄清楚它是如何运作的;所以我想写一个基本代码: 首先,我有一个定义集:邮政编码(邮政编码城市州)
(define zipcodes '(
(96774 ookala hawaii)
(90001 losangeles california)
(90263 malibu california)
(10044 newyork newyork)
))
我尝试编写一个输入邮政编码并返回城市和州名称的函数,例如:
>(find '10044)
(list 'newyork 'newyork)
>(find '99999)
empty because there is not zipcode like that.
非常感谢...
我不允许使用 LET 函数
i'm very beginner of Scheme and try to figure out how it is functioning; so i want to write a basic code:
first of all i have a definition set: zipcode (ZIPCODE CITY STATE)
(define zipcodes '(
(96774 ookala hawaii)
(90001 losangeles california)
(90263 malibu california)
(10044 newyork newyork)
))
i try to write a function that input is zipcode and return city and state name for example:
>(find '10044)
(list 'newyork 'newyork)
>(find '99999)
empty because there is not zipcode like that.
Thanks a lot...
I'm not allowed to us LET function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这对你有用。过滤器会将其第一个参数(过程)应用于其第二个参数中的每个项目,该参数需要是一个列表。第一个参数需要为其传递的每个项目返回一个布尔值。然后,过滤器将返回一个列表,其中包含应用第一个参数时返回 true 的所有项目。否则,它返回一个空列表。
在这种情况下,您传递的列表中的每个项目本身就是一个包含 3 个项目的列表,因此它将该列表中的第一个项目与您要查找的邮政编码进行比较。如果匹配,则返回 true。因此,如果邮政编码在列表中,它将返回三项子列表。然后我们检查是否有空列表,如果是,则返回一个空列表。否则,我们将使用汽车的 cdr 来获取您想要的城市和州。
I think that will work for you. Filter will apply its first argument (a procedure) to each item in its second argument, which needs to be a list. The first argument needs to return a boolean value for each item it's passed. Filter will then return a list with all of the items that returned true when the first argument was applied. Otherwise, it returns an empty list.
In this case, each item in the list you're passing is itself a list of 3 items, so it compares the first item in that list with the zip code you're looking for. If it's a match, it returns true. So if the zip code is in the list, it will return the three item sub-list. Then we check to see if we got an empty list, if so, then we return an empty list. Otherwise, we take the cdr of the car to get your desired city and state.
好吧,你基本上可以只过滤邮政编码列表,我在下面概述了一些代码(我会以不同的方式编写它,除了我不知道在 RnRS 中定义的内容之外你还可以使用什么)。
如果您使用 let 可能会更好,而且我认为大多数实现都有一个过滤器函数,可以让您做得更好。
Well so you can basically just filter the list for the zip code, I have sketched some code below (I'd write it differently, except I don't know what you have available outside of what is defined in RnRS).
It would probably be better should you use a let, and I think most implementations have a filter function that let you do this better.
使用关联
Use
assoc