Lisp Append Not Working Properly

别说谁变了你拦得住时间么 提交于 2019-12-20 03:17:56

问题


Hi I am trying append a simple element to a lisp list.

(append queue1 (pop stack1))

I thought the above code would append the first element of stack1 to queue1. Does queue1 need to be non nil? Thanks.


回答1:


Append returns the concatenated list (queue1 with the first element of stack1 appended). It does not modify queue1.

The destructive equivalent of append is nconc: this appends to the list "in place."




回答2:


You did not specify which Lisp do you mean, but in Common Lisp at least:

  1. APPEND concatenates lists, so all its arguments has to be lists, not atoms. If you really wanted to append an element to the list you would have to do (append list1 (list element)). This is not a good idea because in most Lisps lists are single linked, and an entire list will have to be traversed to append to the end. Usually one would append to the front with CONS and then reverse the list when done, but this obviously will not work for queues.

  2. APPEND does not modify its arguments. NCONC is a destructive function. While I believe that NCONC in particular is specified to do more or less what one would expect, most destructive functions are allowed to destroy their arguments, to reuse their memory, but no necessarily leave anything coherent behind.

  3. Lists in Common Lisp are implemented as chains of cons cells or nil, which means that their behaviour has some quirks relating to the latter. If you want a list acting more as you would expect from other languages then use a list abstract data structure. More so if you want a queue with constant append to the end. There are many imperative data structures available in cl-containers system, and functional data structures in FSet.



来源:https://stackoverflow.com/questions/1569999/lisp-append-not-working-properly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!