-2

Immutable variable: a type of variable that stores it's original version if it is modified. Question: how do I access the older version of that variable in Python? or in Java? or any other languages that support this "persistent data structure?" or am I wrong about the definition of Immutable variables?

After I change a variable in, let's say ,python:

name = "nice name"
name = "bad name"

now, how do I retrieve the older value of var name?

Note: This question is different from the one it has been marked as duplicate of because, this question is about the memory location of variables and the other question is about the scope of variables.

Arpan Adhikari
  • 127
  • 1
  • 9

1 Answers1

0

In your example, name is a reference that points to a value.

In your first line, name points to the immutable string "nice name".

Then in your second line, you update name to point to a different immutable string "bad name".

At this point, no variable references "nice name" - so it is no longer available.

The str type is immutable because the "nice name" value itself cannot be updated. Any operation on a string will create a new block of memory to store the modified string in. In your example, "nice name" and "bad name" are stored in different blocks of memory - all that you are updating is the reference to the memory block.

jlb83
  • 1,988
  • 1
  • 19
  • 30
  • so, the only way to keep that value is to give the old pointer to another variable? – Arpan Adhikari Jan 25 '15 at 13:08
  • If so, what is the significance of that "**previous block of memory**"? – Arpan Adhikari Jan 25 '15 at 13:09
  • If you have a variable pointing to the memory, then you can still access it. But once you have no variable pointing to the memory, the memory is considered unreferenced and will be [garbage collected](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) i.e. cleared without you needing to explicitly ask for it. – jlb83 Jan 25 '15 at 16:35
  • thank you! that helps, I have one last question, is this persistent data structure a designed feature of programming languages? or is it a limitation? i mean "defect"? – Arpan Adhikari Jan 25 '15 at 22:37
  • 1
    It depends on your point of view. To a functional programmer, immutable variables and persistent data structures are normal, and mutation is a "defect." Imperative and object-oriented programmers disagree. But I can't explain that in a 600-character comment, or even in a full StackOverflow answer. You should read a few books about functional programming before you decide that immutable variables are a "defect." – user448810 Jan 25 '15 at 23:46