From SICP:

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

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))
      (+ (pascals-triangle (- row 1)
                            (- col 1))
          (pascals-triangle (- row 1)

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))
        ((or (= col 1) (= col (- row 1)))
      (else (+ (pascals-triangle (- row 1)
                                  (- col 1))
                (pascals-triangle (- row 1)

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?


You should memoise the recursive call in order to make it faster. Since each value has a computational sibling (its value is derived from (one or two) parents which also each has another child), you remove the double-computation that would occur.

Additionally, these double-computations would actually accumulate exponentially up the levels, so it's no longer just a micro-optimisation; it actually affects the your runtime complexity. So it's even more important to implement memoisation.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.