Mutation: changing something already there

Concepts explained

Mutation means changing an existing value’s contents. A mutable collection allows this. An immutable value does not allow its contents to be edited in place.

Pliro lists and maps can be changed. Text values are immutable: you can give a variable different text, but you cannot replace a character by assigning to a text index.

Two names, one list

# language: en
let scores = [2, 5]
let other = scores
set other[0] = 9
say scores[0]

The answer is 9. Both names refer to the same list. The assignment did not copy its contents into a separate list. This shared name is sometimes called an alias.

Replacing a name’s value

Changing other to a newly written list, such as set other = [7, 8], would make that name refer to the new list. It would not replace the contents of scores. Reassigning a variable and changing a shared collection are different operations.

A shallow copy makes a new outer collection but may still share collections nested inside it. A deep copy also copies those nested collections. Read the sharing reference before assuming a function has copied your data.

Try predicting what happens if the changed index is 1 instead of 0. Which list item does each name show afterward?

Assignment · Side effects