Corecursion不会在小变化后终止

时间:2016-02-02 19:48:41

标签: racket fractals corecursion

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

Circle Fractal

(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))])))

现在该功能没有终止。 Racket达到其内存限制,没有输出。

在这次改变之后,每个corecursive调用是否都不会接近这个简单的案例?

1 个答案:

答案 0 :(得分:2)

在第一个版本(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))]))