Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Help, a tricky problem

0 views
Skip to first unread message

Austin

unread,
Sep 26, 2008, 3:09:14 AM9/26/08
to
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)))

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

Pascal J. Bourguignon

unread,
Sep 26, 2008, 3:29:03 AM9/26/08
to
Austin <zzw...@gmail.com> writes:

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!"

Austin

unread,
Sep 26, 2008, 3:47:40 AM9/26/08
to
On 9月26日, 下午3时29分, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
> family. Prepare to die!"- 隐藏被引用文字 -
>
> - 显示引用的文字 -

i mean why n decrease beyond 0? On my platform, n turn to -6455,then
report "error:segmentation violation...."

Jussi Piitulainen

unread,
Sep 26, 2008, 4:29:45 AM9/26/08
to
Austin writes:

> 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.

Pascal J. Bourguignon

unread,
Sep 26, 2008, 4:54:23 AM9/26/08
to
Austin <zzw...@gmail.com> writes:

> 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__

Austin

unread,
Sep 26, 2008, 4:58:16 AM9/26/08
to
Yeah,thank you all.
0 new messages