How to replace an item by another in a list in DrScheme when given paramters are two items and a list?

╄→гoц情女王★ 提交于 2019-12-02 07:11:33

问题


How to replace an item by another in a list in DrScheme when given paramters are two items and a list?


回答1:


Use map with a function which returns the replacement item when its argument is equal to the item you want to replace and the argument otherwise.




回答2:


; replace first occurrence of b with a in list ls, q? is used for comparison
(define (replace q? a b ls)
  (cond ((null? ls) '()) 
    ((q? (car ls) b) (cons a (cdr ls)))
    (else (cons (car ls) (replace a b (cdr ls))))))



回答3:


; replace first occurrence of b with a in list ls, q? is used for comparison
(define (replace q? a b ls)
  (cond ((null? ls) '()) 
        ((q? (car ls) b) (replace q? a b (cons a (cdr ls))))
        (else (cons (car ls) (replace a b (cdr ls))))))



回答4:


This replaces all the occurrences of fsym in the list lst to the symbol tsym in DrRacket

(define (subst fsym tsym lst)

(cond

[(null? lst) lst]

[eq? (first lst) fsym)(cons tsym (subst fsym tsym (rest lst)))]

[else (cons (first lst)(subst fsym tsym (rest lst)))]))

(subst 'a 'b '(f g a h a))

;the results will be as follows.

'(f g b h b)


来源:https://stackoverflow.com/questions/4761285/how-to-replace-an-item-by-another-in-a-list-in-drscheme-when-given-paramters-are

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!