添加向量元素(方案 R5RS)- 请参阅修订后的代码部分
我想在方案中添加向量中的所有项目。
我相信我的问题在于我使用 lambda 的方式(非常不确定这个表达式的正确用法),将向量的长度分配给变量 i 并添加我尝试从向量中的每个元素获取的值。根据错误消息不确定如何修复错误。
我得到的错误只是:
#<程序>
代码:
(define (sum X)
(define length (vector-length X)) ;potential problem area
(lambda (length)
(lambda (total)
(do (
(i length (- i 1))
(a (vector-ref X i)(+ a total)) ; potential problem area
)
((zero? i) total)
)
)
)
)
修改后的代码(感谢 user479988) - 我删除了 lambda,意识到我不需要它们。并将变量 i 定义为初始 0。
错误是现在输出显示 0。
The code:
(define (sum X)
(define length (vector-length X)) ;potential problem area
(define total 0)
(define i 0)
(do (
(i length (- i 1))
(a (vector-ref X i)(+ a total)) ; potential problem area
((zero? i) total)
)
)
)
您能否建议一下 一)错误 ii)算法的逻辑
谢谢!
I'd like to add all items in a vector in Scheme.
I believe my problem areas are in the way I use lambda (very unsure of this expression's correct usage), assign the length of the vector to variable i and add the value I attempt to get from each of the elements in the vector. Not sure how to fix the error based on the error message.
The error I am getting is just:
#< procedure>
the code:
(define (sum X)
(define length (vector-length X)) ;potential problem area
(lambda (length)
(lambda (total)
(do (
(i length (- i 1))
(a (vector-ref X i)(+ a total)) ; potential problem area
)
((zero? i) total)
)
)
)
)
Revised code (thanks user479988) - I've removed the lambdas, realized I dont need them. And defined the variable i to an initial 0.
The error is now the output is showing 0.
The code:
(define (sum X)
(define length (vector-length X)) ;potential problem area
(define total 0)
(define i 0)
(do (
(i length (- i 1))
(a (vector-ref X i)(+ a total)) ; potential problem area
((zero? i) total)
)
)
)
Could you please advise on the
i) error
ii) logic of the algorithm
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法真正告诉你的程序的结构,因为括号不匹配并且缩进很难阅读,但我认为你没有给 lambda 任何输入,所以你不是返回总和,而是返回用lambdas 因为你没有评估它们。
I can't really tell the structure of your program because the parenthesis are mismatched and the indentation is hard to read but I think you're not giving the lambdas any input so instead of returning the sum, you return the function you made with the lambdas since you didn't evaluate them.