Lisp Addition does not work as expected

Hi I am trying to add a simple item to a lisp list.
(append queue1 (pop stack1))

      

I thought the above code would add the first item of stack1 to queue1. Should queue1

n't zero be? Thank.

+2


source to share


2 answers


Append returns the concatenated list ( queue1

with the first item appended stack1

). It does not modify queue1.



The destructive equivalent of append is nconc: it is appended to the list "in place".

+4


source


You haven't specified which Lisp you mean, but in Common Lisp at least:



  • APPEND concatenates lists, so all of its arguments must be lists, not atoms. If you really want to add an item to the list, you will need to do (append list1 (list element))

    . This is not a good idea, because in most lists the Lisps are singly linked and the entire list must go to the end. Usually one of them joins the front with CONS and then cancels the list when done, but this obviously won't work for queues.

  • APPEND does not change its arguments. NCONC is destructive. While I believe NCONC in particular is stated to do more or less than what one would expect, most destructive functions are allowed to destroy their arguments in order to reuse their memory, but not necessarily leave anything consistent.

  • Lists in Common Lisp are implemented as strings of cons cells or nil, which means that their behavior has some quirks associated with the latter. If you want a list to behave more like you would expect from other languages, use the abstract data structure of a list. What's more, if you want a continually appending queue to the end. There are many imperative data structures available in cl-containers , and functional data structures in FSet .

+1


source







All Articles