ldct / isicp

Interactive Structure and Interpretation of Computer Programs
http://www.xuanji.li/isicp/
MIT License
1.16k stars 162 forks source link

Exercise 1.12 gives out an wrong answer #65

Closed soulomoon closed 7 years ago

soulomoon commented 7 years ago

The quiz is:

Exercise 1.12. The following pattern of numbers is called Pascal's triangle.

The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it.       1      1 1     1 2 1    1 3 3 1   1 4 6 4 1        . . .

Write a procedure that computes elements of Pascal's triangle by means of a recursive process. If a number lies outside of the triangle, return 0 (this makes sense if we view pascal as the combination > > function ). Start counting rows and columns from 0.

I did the Exercise, it gave me an unexpected evaluation,so I try to figure it out why. End up copying the answer hided in the html, the site evaluates it to be right, I check in DrRacket with the folowing code. The answer hided in the site is wrong, #the followings.

; site's answer
(define (pascal row col)
   (cond ( (or (< row col)) 0)
         ((or (= 0 col) (= row col)) 1)
         (else (+ (pascal (- row 1) col)
                  (pascal (- row 1) (- col 1))))))
; the right one
(define (ps row col)
  (cond ((or (< row col)
             (< row 1)
             (< col 1)) 0)
        ((or (= col 1)
             (= col row)) 1)
        (else (+ (ps (- row 1) (- col 1))
                 (ps (- row 1) col)))
  )
)
(define (printPs-iter func row col limit)
  (if (and (= row 1) (= col 1)) (display func))
  (if (< row limit) (display (func row col)))
  (if (= row col) (newline))
  (cond ((> row limit) "end")
        ((> row col) (printPs-iter func row (+ col 1) limit))
        ((= row col) (printPs-iter func (+ row 1) 1 limit)))
  )
(define (printPs func limit)
  (printPs-iter func 1 1 limit)
)
(display "----------------") (newline)
(printPs pascal 5)
(display "----------------") (newline)

(display "----------------") (newline)
(printPs ps 5)
(display "----------------") (newline)

terminal print out:

----------------
#<procedure:pascal>1
21
331
4641

"end"
----------------
----------------
#<procedure:ps>1
11
121
1331

"end"
----------------
> 
soulomoon commented 7 years ago

Sorry I think I missed out the fact that col is actually starting from 0 instead of 1 here in the scripts of the site, close the issue