List 在Scheme中,如何用另一个列表的元素替换列表中的元素?

List 在Scheme中,如何用另一个列表的元素替换列表中的元素?,list,scheme,switch-statement,List,Scheme,Switch Statement,因此,函数应该有3个参数,都是字符串。第一个是原始字符串。第二个是字符串中应该更改的字母。第三个是字母应该改成什么。比如说, ~ (switch-up "aabcc" "abc" "def") “ddeff” 我甚至不知道如何从这个开始。有什么帮助吗?概述:创建从旧字母到新字母的映射。浏览原始列表,用新字母替换每个旧字母。假设所有参数都是列表(否则需要string->list): 这看起来像是家庭作业,所以我会给你一些提示,使用你可以使用的程序来解决这个问题。首先,将问题分解为更简单的部分-首

因此,函数应该有3个参数,都是字符串。第一个是原始字符串。第二个是字符串中应该更改的字母。第三个是字母应该改成什么。比如说,

~ (switch-up "aabcc" "abc" "def")
“ddeff”


我甚至不知道如何从这个开始。有什么帮助吗?

概述:创建从旧字母到新字母的映射。浏览原始列表,用新字母替换每个旧字母。假设所有参数都是列表(否则需要
string->list
):


这看起来像是家庭作业,所以我会给你一些提示,使用你可以使用的程序来解决这个问题。首先,将问题分解为更简单的部分-首先,实际的
切换过程基本上迭代输入字符串中的每个字符,依次处理每个字符并使用结果构建新字符串。提示:使用
string ref
substring
检索字符串中的第一个字符和其余字符-将其视为字符串的
car
cdr

(define (switch-up lst letters replacements)
  (if <???>                                      ; if the string is empty
      <???>                                      ; return the empty string ""
      (string-append (replace <???> <???> <???>) ; otherwise string-append the replacement of the first character in the string
                     (switch-up <???> letters replacements)))) ; and advance the recursion over the rest of the string
最后,我发现在前面的过程中定义一个helper过程非常有用,该过程返回
ls
字符串中的字符索引(如果在字符串中找不到该字符,则返回
#f
),因此很容易在替换字符串中找到它。提示:使用
string->list
str
转换为字符列表非常有用

(define (index-of str c)
  <???>) ; ToDo: return the 0-based index of c inside str

备选方案:如果首先将字符串转换为字符列表(使用
string->list
),然后在最后使用
list->string
将其转换回字符串,则问题可能更容易解决。参数是列表还是字符串?在这一点上,问题是矛盾的。另外,您可以使用高级程序(例如,
string ref
)还是仅限于基本程序?对不起。参数是字符串。我想我只限于基本的问题。好的,我根据更新后的问题修改了我的答案。基本上是一样的。另一种选择是首先将字符串转换为字符串列表,然后对其进行操作?定义在哪里?在这里:
(let((idx(ls c的索引))
它是在第二个字符串中找到字符的索引,因此很容易在第三个字符串中找到它
(define (replace c ls rs)
  (let ((idx (index-of ls c)))       ; get the index of c in the `ls` string
    (if idx                          ; if the index was found
        (string (string-ref rs idx)) ; then get the corresponding value from `rs`
        (string c))))                ; otherwise, return c unchanged
(define (index-of str c)
  <???>) ; ToDo: return the 0-based index of c inside str
(switch-up "aabcc" "abc" "def")
=> "ddeff"