Lisp Append Not Working Properly

2019-02-26 03:53发布

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.

标签: lisp append
2条回答
一夜七次
2楼-- · 2019-02-26 04:27

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.

查看更多
小情绪 Triste *
3楼-- · 2019-02-26 04:28

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

查看更多
登录 后发表回答