方案递归错误
这个递归函数似乎工作正常,将我想要的确切字母 B 和 C 添加到结果列表中,然后当它完成时,它正确地看到已到达最后一个元素。
然后它执行基本情况,并发生一个我无法解释的错误。是什么导致了这个错误?
(define(preceding-R X Vector result)
(if (eq? '() (cdr (vector->list Vector)))
result
(helper X Vector result)))
(define (helper X Vector result)
(if(eqv? X (cadr (vector->list Vector))) ((set! result (cons result (car (vector->list Vector)))) (preceding-R X (list->vector (cdr (vector->list Vector))) result))
(preceding-R X (list->vector (cdr (vector->list Vector))) result)))
(preceding-R 'a #(b a c a) '()))
错误:
程序应用:预期程序,给定:#;参数为:((() . b) . c)
This recursive function seems to work properly, adding to the result list the exact letters I want it to, B and C, and then when it finishes, it correctly sees that the last element has been reached.
It then executes the base case, and an error occurs which I cannot explain. What is causing this error?
(define(preceding-R X Vector result)
(if (eq? '() (cdr (vector->list Vector)))
result
(helper X Vector result)))
(define (helper X Vector result)
(if(eqv? X (cadr (vector->list Vector))) ((set! result (cons result (car (vector->list Vector)))) (preceding-R X (list->vector (cdr (vector->list Vector))) result))
(preceding-R X (list->vector (cdr (vector->list Vector))) result)))
(preceding-R 'a #(b a c a) '()))
The error:
procedure application: expected procedure, given: #; arguments were: ((() . b) . c)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一些代码并不是“绝对可怕”:
Eli Barzilay 有一个观点;如果我对原始代码进行评分,我可能会授予不到一半的学分,因为他指出了以下几点:
set!
,并且通常不允许涉及基本的家庭作业问题方案代码。必须使用set!
通常表明递归还没有被很好地理解。begin
“丢弃”除最后一个表达式之外的所有内容的结果,这意味着非尾部表达式具有副作用(如set!
),因此begin
通常也不会出现在教育问题中。(preceding-R 'a #()) =>;错误:尝试将 cdr 应用于 '()
set!
来修改结果,则没有理由传递结果。这是额外的行李。。
节省一些重复的代码。
Here's some code that isn't "absolutely horrible":
Eli Barzilay has a point; if I were grading the original code, I would probably award fewer than half credit because of the things he pointed out:
set!
should be avoided in most circumstances, and is generally not permitted on homework problems involving basic Scheme code. Having to useset!
is a usual tell that recursion isn't understood too well.begin
"throws away" the results of everything but the last expression, it means that the non-tail expressions had side-effects (likeset!
) and sobegin
usually doesn't show up in educational problems either.(preceding-R 'a #()) => Error: Attempt to apply cdr on '()
set!
to modify result, then there's no reason to pass result around. It's extra baggage..
saving some repeated code.
我添加了开始通话。如果你想要多个表达式,如果你不能将它们包装在 () 中,它会被解释为对 void 的函数调用(由 set 返回!),参数由对前面的 -R 的递归调用返回。
I've added begin call. If you want multiple expressions in if you can't just wrap them in (), it was interpreted as function call on void (returned by set!) with argument returned by recursive call to preceding-R.