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?
(<= i n)
to(< i n)
. – Yuval Filmus Sep 19 '21 at 07:03