为什么在Guile中定义递归显示过程会导致无限循环?

huangapple go评论52阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年1月8日 22:28:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定