You are viewing a single comment's thread from:

RE: Building a fully Immutable Stack in C# - Includes SBD 0.001 puzzle buried in the article :)

in #programming7 years ago

Good contents...
I think you did typo error

var book = ImmutableStack<int>.Empty.Push(4).Push(2);
var updated = book.Push(5);

book.Push(5) means "PUSH 5 on book", so you may think book is (5,4,2)
Actually book.Push(5) returns new stack.

Let's see the expression : ImmutableStack.Empty.Push(4).Push(2);
Stack.Push(4) returns something, that means Stack.Push() doesn't change Stack itself.
If Push() changes the Stack, Push() will return nothing.
This is the common rule of making APIs.

Immutable list comes from LISP (functional programming)
Adding an element in front of the list keeps element-sharing and list-immutability.

Sort:  

That is the nature of immutability, yep, the push returns a new stack with 5 on the head of book, It forks the chain like a fork in blockchain, the 4 2 are common in updated along with the storage infrastructure. I mention this in the notes after that snippet but might not have been clear enough :)

The big mistake people not used to immutability might make is

book.push(5);

thinking book is updated. It has forked as has each call to push. Similar if you make an immutable ATV and change it the original tree is as is and a new copy is built with just the required tree rebuilt :)

If you look after a push/pop I always keep the new returned stack. I am a fan of functional but lisp has too many brackets for me :)

I have edited the name "updated" to read "newStack", I think that is more explicit :)

Just shows how variable names can have a huge impact :)

Coin Marketplace

STEEM 0.18
TRX 0.14
JST 0.030
BTC 58639.60
ETH 3167.30
USDT 1.00
SBD 2.43