I solve it by php,and it works.but I try to use scheme,I receive the " Aborting!: maximum recursion depth exceeded" error. I use MIT/GNU Scheme microcode 15.3 .Here is the code.
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;
}
scheme
(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)
)
Your Scheme version isn't quite correct. It's more like this PHP version:
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)) );
}
Perhaps this is a better version:
(define (cc a b)
(cond ((= b 1) a)
((odd? b) (+ a (cc a (- b 1))))
(else (cc (double a) (halve b)))))
Notice the identation reflects the move of )
from the first line of cond
to the very last.