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

后端 未结 4 525
轻奢々
轻奢々 2021-01-21 18:42

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

相关标签:
4条回答
  • 2021-01-21 19:24

    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)
    
    0 讨论(0)
  • 2021-01-21 19:32

    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.

    0 讨论(0)
  • 2021-01-21 19:33
    ; 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))))))
    
    0 讨论(0)
  • 2021-01-21 19:35
    ; 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))))))
    
    0 讨论(0)
提交回复
热议问题