简体   繁体   中英

immutability of data structures and variables in functional programming

It's usually said that in functional programming data structures are immutable. I know that immutable data structure is a data structure that cannot be changed.

However, does it also mean that variable references also can't be changed?

For example,

var arr = [1,2,3]

arr = [4,5,6]

In this code I didn't change the array [1,2,3], but created a new one. Still, I changed the reference of the variable 'arr'. Does this code follow the principle of immutability data structure?

You shouldn't reassign references. Ideally you'd create a new variable so you can see a "before and after" of any changes you've made.

The underlying structure can still be immutable however, even if the reference pointing to it changed. If someone was looking at an old version of the structure, reassigning a reference wouldn't do anything to harm the validity of the data, since the old version still exists, unchanged.

Does it also mean that variable references also can't be changed?

Yes. They're called constants then. You'd better write

const arr1 = [1,2,3] 
const arr2 = [4,5,6]

This approach allows you to treat the scope environment as an immutable datastructure as well, and this should be the default. It makes reasoning about your code a lot easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM