【发布时间】:2020-10-11 00:15:53
【问题描述】:
我正在尝试使用递归创建帕斯卡三角。我的代码是:
(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 三角形的全新代码)。提前致谢! pascal 3 的输出应该是: (1) (1 1) (1 2 1)
【问题讨论】:
-
我使用
(display (add '1 (coresublist (last '((1)(1 1))))))自己测试了较小的函数,得到了正确的输出。 -
“正在寻找帮助我修复此代码的人(不是为我编写全新的代码)”。但恐怕当前的代码需要大量重写。它有语法错误,而且算法一开始就不正确。好像没救了,反正你得从头开始。
-
这能回答你的问题吗? Pascal's Triangle Row Sequence
标签: recursion racket pascals-triangle