From SICP:
Exercise 1.12: The following pattern of numbers is called Pascal’s triangle.1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
. . .
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. Write a procedure that computes elements of Pascal’s triangle by means of a recursive process.
Here is my code:
(define (pascals-triangle row col)
;; "The numbers at the edge of the triangle are all 1"
(if (or (= col 0) (= col row))
1
(+ (pascals-triangle (- row 1)
(- col 1))
(pascals-triangle (- row 1)
col))))
I noticed that the edges of the triangle after 1 is (probably) always the number of rows, because we always add 1 to them when we go to the next row. So I rewrote the code with a minor change.
(define (pascals-triangle row col)
(cond ((or (= col 0) (= col row))
1)
((or (= col 1) (= col (- row 1)))
row)
(else (+ (pascals-triangle (- row 1)
(- col 1))
(pascals-triangle (- row 1)
col)))))
In my previous code, if the colum is 0, the running time is constant. Now in the revised code, it's also constant if the column is 1. And since this is recursive, I am guessing I saved a few steps. Will making small changes like that have a significant impact with my code and systems a lot larger than this?
How can I improve this code?