我的问题是如何编码
(triangle 5) produces (list "*****" "****" "***" "**" "*")
注意:(5 个星号 4,然后 3 然后 2 然后 1)。到目前为止,我有:
(define (triangle n)
(cond
[(zero? n) empty]
[else (cons n (triangle (sub1 n)))]))
但这只会给我 (list 5 4 3 2 1)
。请注意,这仅使用基本的方案初学者列表和缩写。谢谢!
最佳答案
将一个复杂的问题分解成更简单、更短的子部分总是一个好主意。在这种情况下,我们可以通过首先编写子问题的解决方案来简化通用解决方案,如下所示:
- 首先,构建一个创建字符串列表的过程,其中字符串是
"*****"
或"****"
或 .. . 或"*"
- 其次,编写一个
repeat
帮助程序,给定一个字符串和一个数字,重复该字符串多次 - 例如:(repeat "*"3)
将返回"***"
很容易看出第一个子问题如何用第二个子问题来表达。因为这看起来像是一项作业,所以您不应该在这里要求完整的解决方案。自己找答案会更有用,大致思路如下,填空:
(define (triangle n)
(cond [<???> <???>] ; if n is zero return the empty list: '()
[else ; otherwise
(cons <???> ; cons n repetitions of * (using `repeat`)
(triangle <???>))])) ; and advance the recursion
(define (repeat str n)
(cond [<???> <???>] ; if n is zero return the empty string: ""
[else ; otherwise
(string-append <???> ; append the given string
(repeat <???> <???>))])) ; and advance the recursion
如果仔细观察,两个过程共享完全相同的结构。变化的是在基本情况下返回的值(一个空列表和一个空字符串)和用于将部分答案粘在一起的过程(cons
和 string-append
) .
关于scheme - 在初学者方案中,我如何将变量表示为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328085/