Purity implies that the function cannot make destructive updates, so if
xs ++ [a]
is fully evaluated, a copy of xs
must be made. That can happen in constant space if xs
is lazily generated and not referenced anywhere else, so that it can be garbage collected as it is created. Or it can need a copy besides xs
- but purity allows the cells of both lists to point to the same data, so the data need not be copied, only the spine (amended by the final cons). But if a copy is made, the old value xs
is still available.
Also can changing xs ++ [a] to a:xs consumes less memory?
Yes, that one can simple reuse xs
, all that needs is to create a new list cell and let its tail pointer point to xs
.
From a comment:
I don't want C++ function to be pure. I want it to change the state of input. And that is what I wanted to be the whole point of the question.
In that case, you need an impure function/action. That is possible for some data structures to implement, but for lists, the cells have to be copied/constructed anew. But adding an element to a std::vector<T>
may also need reallocation.