(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1)
(A x (- y 1))))))
I understand everything up until the else.
HALP.
Name:
Anonymous2010-07-22 20:56
By that I mean, it calls itself with the first line of the else, but would it ever get to the second line? It keeps calling itself until one of the conditions is met at the first line. Why is there a second line if it's never used?
>>3
Sorry, it's copypasted straight from my SICP pdf.
(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1)
(A x (- y 1))))))
Name:
Anonymous2010-07-22 21:05
>>6
Ha, fuck my face. The formatting in the reply box is shit.
>>2
Read about the COND form.
Here's I'll show you an expansion of a COND form, so you'd understand how it works:
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(t (A (- x 1)
(A x (- y 1)))))
=>
(if (= y 0)
(begin 0)
(cond ((= x 0) (* 2 y)) ((= y 1) 2) (t (a (- x 1) (a x (- y 1))))))
=>
(if (= y 0)
(begin 0)
(if (= x 0)
(begin (* 2 y))
(cond ((= y 1) 2) (t (a (- x 1) (a x (- y 1)))))))
=>
(if (= y 0)
(begin 0)
(if (= x 0)
(begin (* 2 y))
(if (= y 1)
(begin 2)
(cond (t (a (- x 1) (a x (- y 1))))))))
=>
(if (= y 0)
(begin 0)
(if (= x 0)
(begin (* 2 y))
(if (= y 1)
(begin 2)
(begin (a (- x 1) (a x (- y 1)))))))
(cond
(test1 result1)
...)
=>
(if test1
(begin result1)
(cond ...))
Name:
Anonymous2010-07-22 21:09
In the event you reach the else case, [code](A x (- y 1))[/code will be called and its return value is used as the second argument in the other recursive call. What's there to understand? Is it that you want to know the purpose of the function?
Name:
Anonymous2010-07-22 21:15
>>9
I meant the second line of the else, not the entire definition. Because the procedure calls itself in the first expression after else, wouldn't it be impossible to get to the second expression after else, regardless of input?
Name:
Anonymous2010-07-22 21:18
>>10 its return value is used as the second argument in the other recursive call
Ah, that's what I wanted to know, many thanks.
Name:
Anonymous2010-07-22 21:24
>>12
Wait a second >>10
Would (A x(- y 1)) run before (A (- x 1)) and use it's value as the argument? I would think (A (- x 1)) would run first and use it's value for the argument of (A x(- y 1)).
>>17
I'm using Racket right now, I just fucked up reading the parentheses. I thought it was calling itself two separate times in the else body(clause?), it did not look nested to me whenever I was reading.