scheme - 在初学者方案中,我如何将变量表示为字符串?

标签 scheme racket

我的问题是如何编码

(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)。请注意,这仅使用基本的方案初学者列表和缩写。谢谢!

最佳答案

将一个复杂的问题分解成更简单、更短的子部分总是一个好主意。在这种情况下,我们可以通过首先编写子问题的解决方案来简化通用解决方案,如下所示:

  1. 首先,构建一个创建字符串列表的过程,其中字符串是 "*****""****" 或 .. . 或 "*"
  2. 其次,编写一个 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

如果仔细观察,两个过程共享完全相同的结构。变化的是在基本情况下返回的值(一个空列表和一个空字符串)和用于将部分答案粘在一起的过程(consstring-append) .

关于scheme - 在初学者方案中,我如何将变量表示为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328085/

相关文章:

emacs - Emacs 中的方案编辑 - 模式和键盘布局

binary - 如何将十进制转换为二进制?

scheme - 小Schemer eqlist?功能 - 替代版本?

tree - 算术树的前、中、后顺序 [方案/ Racket ]

functional-programming - 为什么 (car '' (a b)) 评估为“报价”?

functional-programming - 使用方案本身实现内置方案函数 begin(),相同的代码在 MIT-SCHEME 和 Racket 中的行为不同?

functional-programming - SICP 练习 2.19 - 如何扩展它?

scheme - Racket /Lisp 错误 : expected a procedure that can be applied to arguments

dictionary - 通过应用给定的操作将矩阵转换为向量的函数

lisp - 在评估中进行小的修正来扩展 Lisp 的最简单方法是什么?