在方案中进行迭代循环
刚接触这里的计划,我在学习 do 循环时遇到了一些麻烦。我正在尝试创建一个函数,该函数将接受一个对象和一个向量,然后迭代该向量直到找到该对象。当找到该对象时,它将返回一个列表,其中包含向量中该对象之前的所有项目。我的代码如下。它会返回的是 do 循环经历了多少次迭代,而不是我想要的列表。如果有人可以帮助我解决语法问题,我将不胜感激。谢谢! (理想情况下会返回 (1 2))
(define(vector-test-iterative X Vector)
(do ((i 0 (+ i 1))) (< i (vector-length Vector))
(if (eqv? X (vector-ref Vector i))
(= i (vector-length Vector))
(cons (vector-ref Vector i) (ls '())))
ls))
(vector-test-iterative '4 #(1 2 4 3 5))
New to scheme here and I'm having some trouble learning do loops. I am attempting to make a function that will take in an object and a vector, and then iterate through the vector until it find that object. When the object is found, it would then return a list containing all of the items in the vector before the object. My code is below. All it will return is how many iterations the do loop went through, instead of the list I want it to. If anyone could help me with the syntax, I would greatly appreciate it. Thanks! ( ideally this would return (1 2))
(define(vector-test-iterative X Vector)
(do ((i 0 (+ i 1))) (< i (vector-length Vector))
(if (eqv? X (vector-ref Vector i))
(= i (vector-length Vector))
(cons (vector-ref Vector i) (ls '())))
ls))
(vector-test-iterative '4 #(1 2 4 3 5))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 Racket,则无需使用
do
,反正这在阴谋者中从来不流行。有各种各样的迭代器——在文档中查找for
以及以for
开头的东西。例如,您的代码归结为(如果您确实想使用
do
,那么您在测试周围缺少一对括号,并且您应该为累加器添加绑定。)If you're using Racket, then there's no need to use
do
, which was never popular among schemers anyway. There's a whole range of iterators -- look forfor
in the docs, and things that start withfor
. For example, your code boils down to(If you really want to use
do
, then you're missing a pair of parens around the test, and you should add a binding for the accumulator.)使用命名循环的解决方案。比
do
版本更干净(在我看来!),并且应该适用于任何 R5RS 方案:A solution that uses a named loop. Cleaner (in my opinion!) than the
do
version and should work on any R5RS Scheme: