list - Racket/Scheme - 根据位置替换列表中的元素
问题描述
我试图定义一个与列表集基本上做同样事情的替换过程。到目前为止,这是我的代码:
(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)
我知道这是由于缺点与附加,但我怎样才能更改我的代码以摆脱额外的括号和 . ?
解决方案
你几乎拥有它!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)
推荐阅读
- r - R:按行值将数据框拆分为几列
- python - 而python中的else不执行else
- android - Cordova 应用程序:“无法实例化活动 ComponentInfo”
- python - 我如何告诉 jsonschem 需要一个/多个 patternProperties?
- c++ - 如何制作使用协议缓冲区的项目?
- php - 你如何让php发送电子邮件
- fastreport - 如何在万神殿的 fastreport 中获取从日期和到日期的输入
- cypress - 如何使用赛普拉斯深入比较 2 个对象
- google-cloud-platform - 使用 Codeigniter 将文件上传到 Google Cloud Storage
- isabelle - 如何查看所有活动的 Isabelle 会话?