Search code examples
recursionschemeracketpascals-triangle

Returning newly created list with 1 element inside function


I'm currently working on building a function that returns a row of Pascal's triangle. My function passes in a list that contains a row in Pascal's triangle and returns the next row depending on which row was passed in. ex. pass in '(1 2 1) and it should return '(1 3 3 1). However I cannot seem to get the beginning 1 in the list.

(define build-next
   (lambda(thisRow)
      (cond
         [(null? thisRow) '(1)]
         [(null? (cdr thisRow)) (cons 1 (cdr thisRow))]
         [else (cons (+ (car thisRow) (car (cdr thisRow))) (build-next(cdr thisRow)))])))

(build-next '(1 2 1))

Running this code will give me the output

'(3 3 1)

without the leading 1


Solution

  • Your functions works if the input row has a zero as first element. Renaming your original function to build-next-helper and introducing a new build-next that simply calls your existing function after prefixing a zero works fine:

    (define build-next-helper
      (lambda (thisRow)
        (cond
          [(null? thisRow)      '(1)]
          [(null? (cdr thisRow)) (cons 1 (cdr thisRow))]
          [else                  (cons (+ (car thisRow) (car (cdr thisRow)))
                                       (build-next-helper (cdr thisRow)))])))
    
    (define (build-next thisRow)
      (build-next-helper (cons 0 thisRow)))
    
    (build-next '(1 2 1))