Corecursion 不会在小改动后终止

Corecursion Doesn't Terminate After Small Change

我在 Racket 中编写了一个函数来生成类似于以下分形的东西。

(define CUT-OFF 5)
(define CIRCLE-MODE "outline")

(define (circle-fractal size colour)
  (local [(define full-circle (circle size CIRCLE-MODE colour))]

    (cond [(<= size CUT-OFF) full-circle]
          [else
           (overlay/align "middle" "middle" 
                          full-circle
                          (beside (circle-fractal (/ size 2) colour)
                                  (circle-fractal (/ size 2) colour)))])))

它通过了我的测试。

我更改了代码,认为下面的代码更具可读性。

(define (circle-fractal size colour)
  (local [(define full-circle (circle size CIRCLE-MODE colour))
          (define half-circle (circle-fractal (/ size 2) colour))]

    (cond [(<= size CUT-OFF) full-circle]
          [else
           (overlay/align "middle" "middle" 
                          full-circle
                          (beside half-circle half-circle))])))

现在函数不会终止。球拍达到其内存限制而没有输出。

在此更改之后,是否每个 corecursive 调用都以某种方式不处理简单的情况?

在第一个版本中 (circle-fractal (/ size 2) colour) 仅在 size > CUT-OFF 时才被评估。在第二个中,它被调用而不管大小。这样你就失去了你的递归基本情况。

尝试:

(define (circle-fractal size colour)
  (define full-circle (circle size CIRCLE-MODE colour))
  (cond [(<= size CUT-OFF) full-circle]
        [else
         (define half-circle (circle-fractal (/ size 2) colour))
         (overlay/align "middle" "middle" 
                        full-circle
                        (beside half-circle half-circle))]))