Value reference and relation to each other

How to understand and what is the idea and name of behaviour described below when using repl:
> f x = x * 2
: number → number
> a = 2
2 : number
> b = f a
4 : number
> a = 10
10 : number
> b
20 : number

Why value of b is beeing considered as an application fo a to f and not just the value f returned even though the type of b is stated as beeing number?

What is the idea and the name of this behaviour?

How to detect if b is simply a number or a value related to some other value, because as long as b is related it seems impossible to assign value of different type to a.

Considering
z = 1
How to write something like
z = z
or
z = f z
where the value of z will be taken as atomic one like the value 1 it holds to have equivalent of z = 1 but when writing z = f z the 1 returned will be “new” one

Are those questions or this kind of thinking misguided towards functional programming?

1 Like

You have found a bit of an unusual situation because the REPL allows you to re-assign variables. While this is useful to enable experimentation in the REPL, “real” Elm programs do not allow re-assignment.

You can see in this mini executable example that the program refuses to compile rather than returning 20: https://ellie-app.com/cjLZkYv2wCJa1

1 Like

Think about the model that you hold in your head that allows you to predict what the code will do.

In Elm, all you have is a set of declarations. You do not have the flow of time from top to bottom. All declarations are simultaneous.

This allows you to write:

b = a + 1 
a = 2 

The order doesn’t matter.

Now, when interacting with the REPL, you also have a set of declarations BUT the REPL allows you to update the set in order to see consequences for different values. When you later say a = 10 it is like saying “but what if a was 10”. The REPL recomputes all values that depend on a.

So, in your example, b is bound to an expression f a. When you update a, b also updates just like if you have all these declarations in a file and you change one of them, recompile and look at the result. You can also update f to something else and it will also change the value in b.

The declarations in the REPL are also bound to the rules of evaluation so, you cannot have recursive declarations like z = z because those kind of declarations expand to infinity.

2 Likes

Thank you for insightful explanation.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.