方案字符串追加?递归复制字符串 [英] scheme string-append? recursion to replicate a string
问题描述
设计一个名为 string-dup 的程序,它使用一个字符串 s 和一个数字 n 并返回一个字符串,该字符串是 s n 次的串联,每个 s 实例之间有空格,即,
Design a program called string-dup that consumes a String s and a Number n and returns a String that is the concatenation of s n times with spaces between each instance of s, i.e.,
(string-dup "a" 3) => "a a a"不使用复制,但我想我们可以使用字符串追加.
(string-dup "a" 3) => "a a a" Without using replicate but i guess we can use string-append.
到目前为止我得到了
(define (string-dup s n)
(cond
[(zero? n) ""]
[else
(cond
[(= n 1 ) s]
[(> n 1 )(string-dup (string-append s " ") (sub1 n))])]))
然而,这只允许我有一个字符串a".我知道你什么时候可以做列表案例
However, this only allows me to have one string "a". I know when in the list case you can do
(cons s (string-cp s (sub1 n)))
但是在这种情况下如何申请?谢谢.
but how to apply in this case? Thanks.
推荐答案
string-dup
的递归调用需要是 string-append
的参数,而不是另一边.这是一个更正(和重构)的版本:
The recursive call to string-dup
needs to be a parameter to string-append
, not the other way round. Here's a corrected (and refactored) version:
(define (string-dup s n)
(cond
[(< n 1) ""]
[(= n 1) s]
[else (string-append s " " (string-dup s (sub1 n)))]))
这篇关于方案字符串追加?递归复制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!