define my own if procedure as:
(define (my-if predicate consequent alternative)
(cond (predicate consequent)
(else alternative)))
then test as:
(my-if (= 5 6) 'yes 'no)
I will get the right answer.
but When I continue to define:
(define (my-factorial n)
(my-if (= n 0)
1
(* n (my-factorial (- n 1)))))
test like: (my-factorial 10), then come the problem that the program
keep on counting down. What's the problem? thx
Try:
(define (my-factorial n)
(display (list 'my-factorial n)) (newline)
(my-if (= n 0)
1
(* n (my-factorial (- n 1)))))
--
__Pascal Bourguignon__ http://www.informatimago.com/
"By filing this bug report you have challenged the honor of my
family. Prepare to die!"
i mean why n decrease beyond 0? On my platform, n turn to -6455,then
report "error:segmentation violation...."
> hi,I am beginner coming across a tricky problem when learning SICP.
> The problem is described as followd:
>
> define my own if procedure as:
> (define (my-if predicate consequent alternative)
> (cond (predicate consequent)
> (else alternative)))
Procedure calls are the most important thing to understand in a
programming language. Here you are learning about _when_ the argument
expressions are evaluated in Scheme: before my-if is actually called.
This is usual, but there are languages that do it differently.
The purpose of my-if, as a conditional, is to avoid evaluating one of
consequent and alternative, but it will be too late.
In contrast, (if p c a) is not a procedure call in Scheme, so it can
follow different rules.
> i mean why n decrease beyond 0? On my platform, n turn to -6455,then
> report "error:segmentation violation...."
Sorry, I meant to trace my-if too.
(define (my-if predicate consequent alternative)
(display (list 'my-if predicate consequent alternative))
(cond (predicate consequent)
(else alternative)))
Now you should see that my-if never gets called.
Remeber what are the rules of evaluation of a function call in scheme!
--
__Pascal Bourguignon__