The less-familiar parts of Lisp for beginners — vector-pop, vector-push, vector-push-extend

The newcomer to Lisp has probably already seen the push and pop operations, that allow the programmer to insert and remove elements at the beginning of a list.  There are also vector equivalents of these, vector-push and vector-pop.  These operations apply to a vector with a fill pointer, and for efficiency reasons act on the last element in the vector, rather than the first.  Note, though, that there are some caveats to be aware of when using vector-push.

Recall that a vector with a fill pointer has a “true” length, and an effective length governed by the fill pointer.  The vector-push operation inserts just past the last element, as determined by the fill pointer, and increments the fill pointer, returning the new value of the fill pointer.  However, if that operation would cause the fill pointer to exceed the actual length of the vector itself, vector-push does nothing and returns nil.  To simplify handling of this case, there is another function, vector-push-extend, that acts just like vector-push, but also increases the length of the vector if that would be necessary to hold the new length (this requires that the vector be adjustable).

Note that vector-push-extend will increase the length of the vector by at least the amount of its extension argument, or a default amount defined by the implementation.  The programmer should take care when supplying this argument.  In SBCL v1.1.14, when no extension is supplied, the default is to double the length of the vector, subject to certain implementation constraints.  Because vector resizing is potentially an expensive operation, in order to avoid scaling issues when pushing large numbers of objects onto a vector it is generally recommended (not just in Lisp) that vectors be resized by a multiple of their length, not by a constant amount.  The programmer should keep this in mind if he or she is planning to supply an extension argument.

Keeping these warnings in mind, the C++ programmer can think of vector-pop and vector-push-extend as being much like the C++ STL std::vector operations pop_back() and push_back().

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.