Andrew Koenig

Dr. Dobb's Bloggers

Containers That Never Change

Last week, I introduced a programming style that never changes the value of a variable once that value has been established. In that article, I made a statement that one reader questioned:

If we try to write this program recursively using the technique we mentioned earlier, we find that each recursive call passes the entire result array as an argument. As a result, the program's runtime will be quadratic in the number of iterations — hardly a happy state of affairs.

This function violates the restriction we wished to impose against changing the value of a variable once such a value was established. Unfortunately, so long as we stick with vectors, it's the best we can do. At least, by using this function, we have been able to encapsulate the idea of appending an element to a vector to create a new vector. However, this function copies all of the elements of v, which means that our collatz_vec function winds up running in quadratic time — because as result grows, all of the vector's elements must be copied on each iteration.

In short, in order to make the recursive collatz_vec function run in a reasonable amount of time, we need some kind of vector-like data structure that allows us to append an element in O(1) time, rather than having to copy all of the elements each time we wish to append one. Putting it more simply, the whole notion of appending rests on being able to change the data structure to which we are appending. What we want is to be able to create a new data structure that contains all of the elements of the old one, along with one additional element, and we wish to do so in O(1) time.

There are many data structures of this kind. Lisp used one of the simpler ones. Next week I'll start explaining how it works.

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!