tags:

views:

228

answers:

2

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.

+2  A: 

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

itowlson
So to append to a list I should simply do (nconc queue1 '4) to append the number 4 to the list queue1. Also what if nconc is nil, will it still append? Thanks
Phillip Whisenhunt
Yes, (nconc queue1 '4) will recycle queue1. Idiomatically however you should still work with the returned value rather than relying on the side-effect. Sorry, I'm not sure what would happen if you passed nil (though I assume it wouldn't work on the nil literal): spin up your Lisp implementation and try it I guess!
itowlson
A: 

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.

Ramarren