Skip to content

Instantly share code, notes, and snippets.

@wantedfast
Last active June 2, 2020 02:35
Show Gist options
  • Select an option

  • Save wantedfast/054ad66a7190ab62aef035a233b24811 to your computer and use it in GitHub Desktop.

Select an option

Save wantedfast/054ad66a7190ab62aef035a233b24811 to your computer and use it in GitHub Desktop.
Personal Learning
**Answer 1:**
The idea behind this library of collections is to provide collections, that when changed produce new versions of the same collection, where all old versions of the collections are still valid.
It is similar to how version control system works: You can change code, and commit changes to the server, producing a new version of the source tree. In the meantime you can still checkout any previous revision.
For immutable collections, you keep acces to an old version (essentially an immutable snapshot) by keeping a pointer to the collection that will not change.
You could argue that this scenario is less useful for a stack because you probably use a stack to add and retrieve each item exactly once, and also preserving the order. Usually a stack's use is very much tied to code running on a single thread of execution.
But now that I'm typing, I can think of a specific use case if you have a lazy parser that needs to track some state in a stack. You can then save a pointer to the immutable stack in the state it was during the initial parse, without copying, and retrieve it when you parse the deferred work.
**Answer 2:**
Imagine a scenario whereby requests are coming in on a single pipeline and are stored in a stack as the last request is to be treated as the priority. Then I have a set of threaded request consumers, each of which deals with a specific type of request. The main marshalling code builds up the stack, then when all the consumers are ready, passes that stack to the consumers and starts a new stack.
If the stack were mutable, each consumer would be running in parallel and would be sharing the same stack that could change at any stage due to the other consumers. Locking would be required to control popping items off the stack to ensure they all stayed in sync. If a consumer takes a long time to complete an action which the stack is locked, all the others are held up.
By having an immutable stack, each consumer is free to do what it wants to the stack without a care for other consumers. Popping an item off the stack results in a new one and the original one is unchanged. So no locking is required and each thread is free to run without a care for the others.
Got this from StackOverflow:https://stackoverflow.com/questions/19024919/use-of-immutable-stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment