【问题标题】:Racket/Scheme - Replacing an element in a list based on a locationRacket/Scheme - 根据位置替换列表中的元素
【发布时间】:2020-09-26 20:10:27
【问题描述】:

我试图定义一个与列表集基本上做同样事情的替换过程。 到目前为止,这是我的代码:

(define replace
  (lambda (s pos lst fin-lst)
    (cond
      ((zero? pos) (cons (cons (reverse fin-lst) s) (rest lst)))
      (else (replace s (- pos 1) (rest lst) (cons (first lst) fin-lst))))))

它有点像它应该做的,但我正在努力让输出看起来像我想要的那样。例如这是我想要的结果

(replace 'a 2 '(1 2 3 4 5) '()) => '(1 2 a 4 5)

但到目前为止,这是我的程序返回的内容

'(((1 2) . a) 4 5)

我知道这是由于 cons 与 append,但我怎样才能更改我的代码以摆脱额外的括号和 . ?

【问题讨论】:

    标签: list append scheme racket


    【解决方案1】:

    你几乎拥有它! reverse 调用放错了位置,您需要使用 append 将两个列表粘在一起。这就是我的意思:

    (define replace
      (lambda (s pos lst fin-lst)
        (cond
          ((zero? pos)
           (append (reverse (cons s fin-lst)) (rest lst)))
          (else
           (replace s (- pos 1) (rest lst) (cons (first lst) fin-lst))))))
    

    它按你的预期工作:

    (replace 'a 2 '(1 2 3 4 5) '())
    => '(1 2 a 4 5)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      (define replace
        (lambda (l pos e)
          ((lambda (s) (s s l pos (lambda(x) x)))
           (lambda (s l i col)
             (if (null? l)
                 (col '())
                 (if (zero? i)
                     (col (cons e (cdr l)))
                     (s s (cdr l) (- i 1)
                        (lambda (r)
                          (col (cons (car l) r))))))))))
      
      
      (replace '(a b c d e f) 2 'x)
      (replace '(a b c d e f) 0 'x)
      (replace '(a b c d e f) 20 'x)
      

      【讨论】:

        猜你喜欢
        • 2011-04-30
        • 2021-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-13
        • 2021-11-21
        • 2019-04-13
        相关资源
        最近更新 更多