←back to thread

498 points azhenley | 1 comments | | HN request time: 0.001s | source
Show context
EastLondonCoder ◴[] No.45770007[source]
After a 2 year Clojure stint I find it very hard to explain the clarity that comes with immutability for programmers used to trigger effects with a mutation.

I think it may be one of those things you have to see in order to understand.

replies(17): >>45770035 #>>45770426 #>>45770485 #>>45770884 #>>45770924 #>>45771438 #>>45771558 #>>45771722 #>>45772048 #>>45772446 #>>45773479 #>>45775905 #>>45777189 #>>45779458 #>>45780612 #>>45780778 #>>45781186 #
ErroneousBosh ◴[] No.45771722[source]
I guess I'm not that good a programmer, because I don't really understand why variables that can't be varied are useful, or why you'd use that.

How do you write code that actually works?

replies(4): >>45771824 #>>45772583 #>>45773343 #>>45787597 #
jimbokun ◴[] No.45773343[source]
The concept is actually pretty simple: instead of changing existing values, you create new values.

The classic example is a list or array. You don't add a value to an existing list. You create a new list which consists of the old list plus the new value. [1]

This is a subtle but important difference. It means any part of your program with a reference to the original list will not have it change unexpectedly. This eliminates a large class of subtle bugs you no longer have to worry about.

[1] Whether the new list has completely new copy of the existing data, or references it from the old list, is an important optimization detail, but either way the guarantee is the same. It's important to get these optimizations right to make the efficiency of the language practical, but while using the data structure you don't have to worry about those details.

replies(1): >>45775639 #
ErroneousBosh ◴[] No.45775639[source]
> It means any part of your program with a reference to the original list will not have it change unexpectedly.

I don't get why that would be useful. The old array of floats is incorrect. Nothing should be using it.

That's the bit I don't really understand. If I have a list and I do something to it that gives me another updated list, why would I ever want anything to have the old incorrect list?

replies(2): >>45775956 #>>45776082 #
1. b_e_n_t_o_n ◴[] No.45775956{4}[source]
State exists in time, a variable is usually valid at the point it's created but it might not be valid in the future. Thus if part of your program accesses a variable expecting it to be from a certain point in time but it's actually from another point in time (was mutated) that can cause issues.