返回每个其他元素的列表的方案过程 [英] A scheme procedure that returns a list of every other element
问题描述
我在 Scheme 中实施这个程序时遇到了一些麻烦,尽管我认为我已经完成了 90%.不幸的是,我需要对此有点含糊,因为这是一项家庭作业.我想 (A B C D ) 返回 ( B D ) .但我收到一个错误,提示作为参数传递给安全车的对象 () 不是一对|"这是我的代码:
I'm having a bit of trouble implementing this program in Scheme, although I think I'm 90% of the way there. Unfortunately I need to be a little vague about it since this is a homework assignment. I want to (A B C D ) to return ( B D) . but i am getting an error that says The object (), passed as an argument to safe-car, is not a pair | " This is my code:
(DEFINE (other_el lis)
(COND
(( NULL? lis ) '())
((LIST? lis)
(append (CADR lis) (other_el (CDR lis))))
(ELSE (show " USAGE: (other_el [LIST])"))))
推荐答案
在我演示正确的代码之前,应该提到这段代码的一些小问题.
There are a number of minor issues with this code that should be mentioned before I demonstrate the proper code.
- 不要将过程的名称大写,例如 cdr 和 Scheme 中的定义.
- 不要手动显示错误消息.使用例外.
- 你应该总是缩进你的代码.(看起来有人编辑了问题的代码以包含缩进)
无论如何,这是您正在寻找的功能:
Anyway, here is the function you are looking for:
(define (evens lst)
(if (or (null? lst) ; if the list is empty
(null? (cdr lst))) ; or the list has a single element
'() ; then return the empty list
(cons (cadr lst) ; otherwise `cons` the second element
(evens (cddr lst))))) ; and recursively advance two elements
我在 DrRacket 5.3 中测试了该函数,并且 (evens '(A B C D)) 返回 '(B D),如您所指定.如果您有任何麻烦,请告诉我.祝你作业顺利!
I tested the function in DrRacket 5.3 and (evens '(A B C D)) returns '(B D), as you specified. If you have any trouble, let me know. Good luck with your homework!
这篇关于返回每个其他元素的列表的方案过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!