开发者

Lisp Append Not Working Properly

Hi I am trying append a simple ele开发者_运维百科ment 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.


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."


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜