更改列表的第n个元素 [英] Changing the nth element of a list

查看:194
本文介绍了更改列表的第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改列表的第n个元素并返回一个新列表.

I want to change the nth element of a list and return a new list.

我已经想到了三种非常精致的解决方案:

I've thought of three rather inelegant solutions:

(defun set-nth1 (list n value)
  (let ((list2 (copy-seq list)))
    (setf (elt list2 n) value)
    list2))

(defun set-nth2 (list n value)
  (concatenate 'list (subseq list 0 n) (list value) (subseq list (1+ n))))

(defun set-nth3 (list n value)
  (substitute value nil list 
    :test #'(lambda (a b) (declare (ignore a b)) t)
    :start n    
    :count 1))

做到这一点的最佳方法是什么?

What is the best way of doing this?

推荐答案

如何

(defun set-nth4 (list n val)
  (loop for i from 0 for j in list collect (if (= i n) val j)))

也许我们应该注意与substitute的相似之处,并遵循其约定:

Perhaps we should note the similarity to substitute and follow its convention:

(defun substitute-nth (val n list)
  (loop for i from 0 for j in list collect (if (= i n) val j)))

关于set-nth3的BTW,有一个函数恒定地这样的情况:

BTW, regarding set-nth3, there is a function, constantly, exactly for situation like this:

(defun set-nth3 (list n value)
  (substitute value nil list :test (constantly t) :start n :count 1))

另一种可能性:

Another possibility:

(defun set-nth5 (list n value)
  (fill (copy-seq list) value :start n :end (1+ n)))

这篇关于更改列表的第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆