1

I am trying to create Pascal's Triangle using recursion. My code is:

(define (pascal n)

(cond
 ( (= n 1)
   list '(1))
 (else (append (list (pascal (- n 1))) (list(add '1 (coresublist (last (pascal (- n 1))))))
)))) ;appends the list from pascal n-1 to the new generated list

(define (add s lst) ;adds 1 to the beginning and end of the list  
(append (list s) lst (list s))
)

(define (coresublist lst) ;adds the subsequent numbers, takes in n-1 list

  (cond ((= (length lst) 1) empty)
        (else 
       (cons (+ (first lst) (second lst)) (coresublist (cdr lst)))

  )))

When I try to run it with: (display(pascal 3)) I am getting an error that says:

length: contract violation expected: list? given: 1

I am looking for someone to help me fix this code (not write me entirely new code that does Pascal's Triangle). Thanks in advance! The output for pascal 3 should be: (1) (1 1) (1 2 1)

Jay
  • 13
  • 3
  • I tested the smaller functions by themselves using `(display (add '1 (coresublist (last '((1)(1 1))))))` and I got the right outputs. – Jay Oct 11 '20 at 00:18
  • "Looking for someone to help me fix this code (not write me entirely new code)". But I'm afraid the current code requires a substantial rewriting. It has syntax errors, and the algorithm isn't correct to begin with. It doesn't look like it can be saved, you'll have to start from scratch anyway. – Óscar López Oct 11 '20 at 02:17
  • 1
    Does this answer your question? [Pascal's Triangle Row Sequence](https://stackoverflow.com/questions/12413619/pascals-triangle-row-sequence) – tjorchrt Oct 12 '20 at 10:56

1 Answers1

2

We should start with the recursive definition for a value inside Pascals' triangle, which is usually expressed in terms of two parameters (row and column):

(define (pascal x y) 
  (if (or (zero? y) (= x y))
      1
      (+ (pascal (sub1 x) y)
         (pascal (sub1 x) (sub1 y)))))

There are more efficient ways to implement it (see Wikipedia), but it will work fine for small values. After that, we just have to build the sublists. In Racket, this is straightforward using iterations, but feel free to implement it with explicit recursion if you wish:

(define (pascal-triangle n)
  (for/list ([x (in-range 0 n)])
    (for/list ([y (in-range 0 (add1 x))])
      (pascal x y))))

It'll work as expected:

(pascal-triangle 3)
=> '((1) (1 1) (1 2 1))
Óscar López
  • 232,561
  • 37
  • 312
  • 386