Pascal's Triangle in Racket

916 views Asked by At

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)

1

There are 1 answers

0
Óscar López On

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))