首页 > 解决方案 > 替换球拍列表中的字符串

问题描述

我试图用另一个给定的字符串替换列表中的字符串,仅使用抽象列表函数和 lambda。该函数使用 lst(字符串列表)、str(要替换的字符串)和 rep(要替换 str 的字符串)。下面是一个例子:(替换 (list "hi" "how" "are" "you") "hi" "bye") -> (list "bye" "how" "are" "you")

下面写的是我在递归中编写的代码,它可以工作。

(define (replace lst str rep)
  (cond [(empty? lst) empty]
        [(equal? match (first lst))
           (cons rep (replace-all (rest lst) match rep))]
        [else (cons (first lst) (replace-all (rest lst) match rep))]))

下面的代码是我尝试过的,但我不确定如何修复它以使其产生我想要的。

(define (replace lst str rep)
   (map (lambda (x) (string=? x str)) lst))

任何和所有的帮助表示赞赏,谢谢!

标签: schemeracket

解决方案


差不多好了!对于每个字符串,您只需要问:这是我要替换的字符串吗?然后替换它 - 否则保持不变:

(define (replace lst str rep)
  (map (lambda (x) (if (string=? x str) rep x)) 
       lst))

推荐阅读