this post was submitted on 15 Apr 2024
397 points (91.6% liked)
Programmer Humor
19511 readers
341 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
So do you create new objects every time you need to change state?
You avoid having mutable state as much as possible. This is a pretty standard concept these days.
Can you please give me an example - let's say I have a big list of numbers and I need to find how many times each number is there.
I would expect a mutable dictionary/map and a single pass through. How would you do that without mutable datastructure?
Very standard use case for a
fold
orreduce
function with an immutable Map as the accumulatorfoldLeft
is a classic higher order function. Every functional programming language will have this plus multiple variants of it in their standard library. Newer non-functional programing languages will have it too. Writing implementations offoldLeft
andfoldRight
is standard for learning recursive functions.The lambda is applied to the initial value (0 or
Map.empty[Int, Int]
) and the first item in the list. The return type of the lambda must be the same type as the initial value. It then repeats the processes on the second value in the list, but using the previous result, and so on until theres no more items.In the example above,
c
will change like you'd expect a mutable solution would but its a new Map each time. This might sound inefficient but its not really. Because each Map is immutable it can be optimized to share memory of the past Maps it was constructed from. Thats something you absolutely cannot do if your structures are mutable.So you have memory space which is reused... Which essentially makes it a mutable memory structure, where you update or add with new data keys... No?
No. Persistent Data Structures are not mutable. The memory space of an older version is not rewritten, it is referenced by the newer version as a part of its definition. ie via composition. It can only safely do this if the data it references is guaranteed to not change.
In this example both
x
andy
are single linked lists.y
is a node with value3
and a pointer tox
. Ifx
was mutable then changingx
would changey
. That's bad™ so its not allowed.If you want to learn more about functional programming I suggest reading Structures and Interpretation of Computer Programs or Learn You a Haskell for Great Good