Recursion 帕斯卡';球拍中的三角
我正在尝试使用递归创建Pascal三角形。我的代码是:Recursion 帕斯卡';球拍中的三角,recursion,racket,pascals-triangle,Recursion,Racket,Pascals Triangle,我正在尝试使用递归创建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
(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)))
)))
当我尝试使用以下工具运行它时:
(显示(pascal 3))
我收到一个错误,上面写着:
长度:违反合同
期望:列表?
给定:1
我正在寻找一个人来帮助我修复这个代码(不是给我写一个完整的帕斯卡三角形的新代码)。提前谢谢!pascal 3的输出应为:
(1) (1 1)(1 2 1)我们应该从帕斯卡三角形内值的递归定义开始,它通常用两个参数(行和列)表示: 有更有效的方法来实现它(请参阅),但对于较小的值,它可以很好地工作。之后,我们只需要构建子列表。在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))
我自己使用
(display(添加'1(coresublist(last'((1)(1 1 1‘‘‘‘))))
测试了较小的函数,我得到了正确的输出。“正在找人帮助我修复此代码(而不是为我编写全新的代码)”。但我担心当前的代码需要大量重写。它有语法错误,而且算法一开始就不正确。它看起来不可能被保存,无论如何你必须从头开始。这回答了你的问题吗?
(pascal-triangle 3)
=> '((1) (1 1) (1 2 1))