SICP 练习 1.17 中止!:超过最大递归深度

SICP Exercise 1.17 Aborting!: maximum recursion depth exceeded

我用php解决了,works.but我尝试使用方案,我收到“中止!:超出最大递归深度”错误。我使用 MIT/GNU Scheme 微码 15.3 .这是代码。

php

function cc($a,$b)
{
    if($b==1){
        return $a;
    }elseif($b%2!==0){
        return $a+cc($a,$b-1);
    }else{
        return cc(double1($a),halve($b));
    }
}
function double1($i)
{
    return 2*$i;
}
function halve($i)
{
    return $i/2;
}

方案

(define (cc a b)
  (cond ((= b 1) a))
  ((odd? b) (+ a (cc a (- b 1))))
  (else (cc (double a) (halve b)))
  )
(define (double n)
  (+ n n)
  )
(define (halve n)
  (/ n 2)
  )

您的 Scheme 版本不太正确。更像是这样 PHP 版本:

function cc($a, $b){
  if ($b === 1) { return $a; }

  call_user_func($b%2!==0, 
                 $a + cc($a, $b-1) );

  return else(cc(double1($a), halve($b)) );
}

也许这是一个更好的版本:

(define (cc a b)
  (cond ((= b 1) a)
        ((odd? b) (+ a (cc a (- b 1))))
        (else (cc (double a) (halve b)))))

注意标识反映了 )cond 的第一行到最后一行的移动。