英文:
Why defining a recursive-display procedure in Guile causes infinite loop?
问题
以下过程会导致无限循环:
(define (recursive-display . args)
(if (null? args)
#t
(begin
(display (car args))
(recursive-display (cdr args)))))
我仍在学习Guile,所以对这种情况感到有些困惑。
英文:
The following procedure causes an infinite loop:
(define (recursive-display . args)
(if (null? args)
#t
(begin
(display (car args))
(recursive-display (cdr args)))))
I'm still learning about Guile so I'm a bit confused why that's the case.
答案1
得分: 3
使用display
来打印args
的值并查看输出:
(define (recursive-display . args)
(if (null? args)
#t
(begin
(display args)
(recursive-display (cdr args)))))
> (recursive-display 1 2 3)
(1 2 3)
((2 3))
(())
(())
(())
...
你的函数recursive-display
具有可变数量的参数。当你像(recursive-display 1 2 3)
这样调用它时,传递给这个函数的所有参数都被包装在列表中,所以变量args
的值是'(1 2 3)
。
接下来,你调用(recursive-display (cdr args))
。同样的规则再次适用-所有参数都被包装在列表中,所以args
现在的值是'((2 3))
。
在所有后续迭代中,args
的值都是'(())
。
当你添加 apply
时,它将按预期工作:
(define (recursive-display . args)
(if (null? args)
#t
(begin
(display (car args))
(apply recursive-display (cdr args)))))
> (recursive-display 1 2 3)
123#t
英文:
Use display
to print the value of args
and look at the output:
(define (recursive-display . args)
(if (null? args)
#t
(begin
(display args)
(recursive-display (cdr args)))))
> (recursive-display 1 2 3)
(1 2 3)
((2 3))
(())
(())
(())
...
Your function recursive-display
has a variable number of arguments. When you call something like (recursive-display 1 2 3)
, all arguments passed to this function are wrapped in the list, so variable args
has a value '(1 2 3)
.
Next, you call (recursive-display (cdr args))
. The same rule applies again- all arguments are wrapped in the list, so args
has now value '((2 3))
.
In all following iterations, args
has a value '(())
.
When you add apply
, it will work as expected:
(define (recursive-display . args)
(if (null? args)
#t
(begin
(display (car args))
(apply recursive-display (cdr args)))))
> (recursive-display 1 2 3)
123#t
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论