Reputation: 3
I'm learning Berkeley CS61A using Scheme. pigl
function is used to introduce recursion and the sample code is as follows
(define (pigl wd)
(if (pl-done? wd)
(word wd 'ay)
(pigl (word (bf wd) (first wd))) ) )
I tried to change if
tocond
expression, the modified code is as follows
(define (pigl2 wd)
(cond ((pl-done? wd) (word wd 'ay))
(else pigl2 (word (bf wd) (first wd))) ) )
Based on my understanding of the interpretation of if
and cond
in SICP, I think these two procedures should be equivalent. However pigl2
didn't work that it gave 'ab
for input 'ba
and the correct answer is abay
.
I don’t know if I misunderstood the evaluation rules of if
and cond
or if I made any other stupid mistakes. Please help me, thanks!
Upvotes: 0
Views: 113
Reputation: 235984
This is your code, commented to highlight the problem:
(define (pigl2 wd)
(cond ((pl-done? wd) (word wd 'ay))
(else
pigl2 ; this line does nothing at all
(word (bf wd) (first wd))))) ; return result of calling `word`
You forgot to actually call pigl2
: it's missing the surrounding brackets! This should fix the problem:
(define (pigl2 wd)
(cond ((pl-done? wd) (word wd 'ay))
(else (pigl2 (word (bf wd) (first wd))))))
Upvotes: 2