2

I was reading SICP and was solving a problem that asked to create a function in lisp for finding elements of Pascal's triangle. The way I went about it is to take input as the row number and then print each element of the row iteratively, whose value would be found recursively.

(define (pascDisp n)
        (define i 1)
    (define (pasc n i)
            (if (or (= i 1)
                    (= i n))
                1
                (+ (pasc (- n 1)
                         (- i 1))
                   (pasc (- n 1)
                         i))))

    (define (pascDispIter n i)
            (display (pasc n i))
            (display " ")

            (if (<= i n)
                (pascDispIter n
                              (+ i 1))))

    (pascDispIter n i))

(pascDisp 5)

This does print out all the elements however, it goes into an infinite loop. I can't seem to find any problem with the logic though. The interpreter shows that (pasc (- n 1) i) is being called infinitely. Can you explain why this is happening?

1 Answers1

2

Your code has an "off by one" mistake: in the $n$'th row, it prints $\binom{n}{1},\ldots,\binom{n}{n+1}$ (the condition i <= n should be corrected to i < n).

This highlights another problem with your code: it implicitly assumes that $1 \leq i \leq n$, which is not necessarily correct (and also has a wrong base case: it should be $\binom{n}{0} = 1$; indeed, $\binom{n}{1} = n$). Instead, you should first check whether $i$ is within bounds, and if not, output zero.

(This will not work with negative binomial coefficients, but you're probably not interested in those.)

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503