帕斯卡的三角拍

问题描述

我正在尝试使用递归创建Pascal三角形。我的代码是:

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

  )))

当我尝试使用以下命令运行它时: (display(pascal 3)) 我收到一条错误消息:

长度:违反合同 预期:清单? 给出:1

我正在寻找可以帮助我修复此代码的人(而不是为我编写执行Pascal Triangle的全新代码)。提前致谢! Pascal 3的输出应为: (1)(1 1)(1 2 1)

解决方法

我们应该从帕斯卡三角形内的值的递归定义开始,该定义通常用两个参数(行和列)表示:

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

有更有效的方法来实现它(请参见Wikipedia),但是对于较小的值,它会很好地工作。之后,我们只需要构建子列表。在Racket中,使用迭代很简单,但是如果愿意,可以通过显式递归来实现它:

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

它将按预期工作:

(pascal-triangle 3)
=> '((1) (1 1) (1 2 1))