EXERCISES OF SICP:CHAPTER 1

it2025-04-12  9

Exercise 1.12 Write a procedure that computes the elements of Pascal's triangle by means of  a recursive process.

Solution: A rather simple task. Apparently the RULE is: the numbers of edge are 1, and the other are the sum of the two numbers above it. In this way it seems easier to understand:

11 11 2 11 3 3 11 4 6 4 1...

The way we determine the number of the triangle is by its potision, in this case, the coordinate (row, col). So we design the function like this:

(pascal-triangle row col)

We observe the  triangle and easily the initialization would be:

(if (or (= row col) (= col 0)1 (;otherwise-start-the-recursion))

The recursion calls the function pascal-triangle again, with the coordinates according to the RULE:

(+ (pascal-triangle (- row 1) (- col 1)) (pascal-triangle (- row 1) col))

At the end, the complete code as follows:

1 (define (pascal-triangle row col)2 (if (or (= col 0) (= row col))3 14 (+ (pascal-triangle (- row 1) (- col 1)) (pascal-triangle (- row 1) col))))

#1 After viewing this article, I think I might just missed one important condition. That is the coordinate the function receives should be valid in the Pascal Triangle, thus version 2:

(define (pascal-triangle row col) (cond ((< row col) #f) ((or (= col 0) (= row col)) 1) (else (+ (pascal-triangle (- row 1) (- col 1)) (pascal-triangle (- row 1) col)))))

转载于:https://www.cnblogs.com/hodezx/archive/2011/07/23/exercises-sicp-chapter-one.html

相关资源:数据结构—成绩单生成器
最新回复(0)