small medium large xlarge

Generic-user-small
09 Mar 2016, 15:06
Mohamed Chenini (6 posts)

I am still confused on when a variable is immutable or not:

in page 204 of programming-elixir-1-2_p1_0, there is statement

{ :reply, current_number, current_number+1 }

does this mean current_number is mutable sine it is incremented by 1?

Can someone clarify please?

Regards, Mohamed

Generic-user-small
09 Mar 2016, 15:25
Mohamed Chenini (6 posts)

I do understand that this can be done in the parameter of a function, because when a function is called it starts with a new initial state. But I would like some explanations on when the variable is mutable.

Dave_gnome_head_isolated_pragsmall
09 Mar 2016, 16:49
Dave Thomas (395 posts)

I think you have to start by deciding what “variable is mutable” means.

As you rightly say, there’s no mutating in this example—the code merely returns a new value.

But Elixir does let you say

var = 99
var = var + 1

Is this mutation?

No, I don’t think so.

What we’re doing here is rebinding a variable. var used to to bound to 99, and then it is bound to 100. We’re not changing the value of 99 itself.

Here’s another way of looking at the difference:

Ruby code:

irb(main):001:0> a = b = [ 1, 2, 3 ]
=> [1, 2, 3]
irb(main):002:0> a
=> [1, 2, 3]
irb(main):003:0> b
=> [1, 2, 3]
irb(main):004:0> a.unshift 99
=> [99, 1, 2, 3]
irb(main):005:0> a
=> [99, 1, 2, 3]
irb(main):006:0> b
=> [99, 1, 2, 3]

Note that changing the value affected both a and b.

In Elixir:

iex(1)> a = b = [ 1, 2, 3 ]
[1, 2, 3]
iex(2)> a = [ 99 | a ]
[99, 1, 2, 3]
iex(3)> a
[99, 1, 2, 3]
iex(4)> b
[1, 2, 3]

There’s no way to change the value bound to b by messing with a. That’s what immutability is.

Davr

You must be logged in to comment