Last active
May 18, 2018 14:01
-
-
Save ShlomoAbraham/2111fa2a61cec26a49e4d6f62793df93 to your computer and use it in GitHub Desktop.
Immutable Collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//uses nuget System.Immutable.Collections | |
//using System.Immutable.Collections; | |
//On an implementation level, an ImmutableQueue is a linked list with head and tail pointers. So q is a reference to an empty list. | |
var q = ImmutableQueue<int>.Empty; //[] | |
//Create a new node, and point it towards the list 'q' (which is empty) | |
var q1 = q.Enqueue(1); // 1. | |
//Create a new node, and point it towards the list 'q1' (which is empty) | |
var q2 = q1.Enqueue(2); // 2 -> q1 (which is equivalent to): 2 -> 1 | |
//Not as smart as could be: Equivalent queues are not reference equal | |
var q2copy = q1.Enqueue(2); // equivalent to q2, but not reference equal | |
var isRefEqual1 = (q2 == q2copy); //returns false | |
Console.WriteLine($"q2 is {(isRefEqual1 ? "" : "not " )}equal to q2copy"); | |
//However, all empty Queues share a reference. | |
var qCopy = q.Enqueue(3).Dequeue(); //Add 3 to the empty queue, then dequeue it, ending with an empty queue | |
var isRefEqual2 = (q == qCopy); //returns true | |
Console.WriteLine($"q is {(isRefEqual2 ? "" : "not ")}equal to qcopy"); | |
Console.WriteLine($"State: q-Node count: {q.Count()}, q1-Node count: {q1.Count()}, q2-Node count: {q2.Count()}"); | |
q.Enqueue(100); //has no effect: Returns a new Queue, doesn't change existing one. | |
q.Enqueue(100); //has no effect: Returns a new Queue, doesn't change existing one. | |
Console.WriteLine($"State: q-Node count: {q.Count()}, q1-Node count: {q1.Count()}, q2-Node count: {q2.Count()}"); | |
q1.Dequeue(); //has no effect: Returns a new Queue, doesn't change existing one. | |
q1.Dequeue(); //has no effect: Returns a new Queue, doesn't change existing one. | |
Console.WriteLine($"State: q-Node count: {q.Count()}, q1-Node count: {q1.Count()}, q2-Node count: {q2.Count()}"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment