在common-lisp中,如何将元素插入到列表中? [英] In common-lisp, how can I insert an element into a list in-place?

查看:85
本文介绍了在common-lisp中,如何将元素插入到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个问题:

1。我想要一个函数在列表内就地插入一个元素(除了列表的开头,其他任何位置,请参见问题2)):

1.I want a function to insert an element inside a list in-place (in any position but the start of the list, see question 2 for the reason) such that:

CL> (defun insert-in-place (the-list after-position new-element) .... ) => ...
CL> (setf testy-list (list 'a 'b 'c 'd)) => ...  
CL> testy-list => ('A 'B 'C 'D)  
CL> (insert-in-place testy-list 1 'BOOOO) => ...  
CL> testy-list => ('A 'B 'BOOOO 'C 'D)

2。我认为将元素插入通过函数无法就地开始列表的开头,因为args是通过值传递的,因此,由于列表的第一个cons单元是通过传递的,因此它是通过值传递的,并且它是一个副本,因此更改其car只会更改共享汽车,而不是原始汽车,尽管以下缺点单元是共享的,并且可以在原地进行更改。我对吗?

2.I think that inserting an element into the start of the list in-place is impossible through a function because the args are passed by value, so since the first cons cell of the list is passed, it is passed by value and it is a copy and so changing its car only changes a copy car, not the original, although the following cons cells are shared and change in place is possible. Am I correct?

推荐答案

1)在这里是:

(defun insert-after (lst index newelt)
  (push newelt (cdr (nthcdr index lst))) 
  lst)
(insert-after '(a c d) 0 'b)   => (A B C D)

2)对cons细胞的破坏性修改:

2) destructive modification of cons cells:

(setf testy-list '(a bar))
(defun modify (list)
  (setf (first list) 'foo))
(modify testy-list)
testy-list   => (FOO BAR)

这会将第一个cons单元格的汽车设置为 foo。

This sets the car of the first cons cell to 'foo.

这篇关于在common-lisp中,如何将元素插入到列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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