????????岻??伯??
?????????????伯?????????????????????????????????м????????????ü?????????????????????ò???伯??????????????????????????????????????????????????????????????????????????????????????????????£?
public interface IStack<T> : IEnumerable<T>
{
IStack<T> Push(T value);
IStack<T> Pop();
T Peek();
bool IsEmpty { get; }
}
public sealed class Stack<T> : IStack<T>
{
private sealed class EmptyStack : IStack<T>
{
public bool IsEmpty { get { return true; } }
public T Peek() { throw new Exception("Empty stack"); }
public IStack<T> Push(T value) { return new Stack<T>(value?? this); }
public IStack<T> Pop() { throw new Exception("Empty stack"); }
public IEnumerator<T> GetEnumerator() { yield break; }
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
}
private static readonly EmptyStack empty = new EmptyStack();
public static IStack<T> Empty { get { return empty; } }
private readonly T head;
private readonly IStack<T> tail;
private Stack(T head?? IStack<T> tail)
{
this.head = head;
this.tail = tail;
}
public bool IsEmpty { get { return false; } }
public T Peek() { return head; }
public IStack<T> Pop() { return tail; }
public IStack<T> Push(T value) { return new Stack<T>(value?? this); }
public IEnumerator<T> GetEnumerator()
{
for (IStack<T> stack = this; !stack.IsEmpty; stack = stack.Pop())
yield return stack.Peek();
}
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
}
?????????????????????????
??????????????????????????????????Headλ???????????????Tailλ??????
????????????????????Tail??????????
??????÷??????£?
????IStack<int> s1 = Stack<int>.Empty;
????IStack<int> s2 = s1.Push(10);
????IStack<int> s3 = s2.Push(20);
????IStack<int> s4 = s3.Push(30);
????IStack<int> v3 = s4.Pop();
????foreach (var item in s4)
????{
????//dosomething
????}
???????Push????????????????????????????????????????????????????????
????Net???????伯??
???????????У???????б??????????????????????????е????????Net??4.5?汾??????????伯????????? ???Nuget?????
????Install-Package Microsoft.Bcl.Immutable
??????????£?????????????????????????
????ImmutableStack<int> a1 = ImmutableStack<int>.Empty;
????ImmutableStack<int> a2 = a1.Push(10);
????ImmutableStack<int> a3 = a2.Push(20);
????ImmutableStack<int> a4 = a3.Push(30);
????ImmutableStack<int> iv3 = a4.Pop();
???????Net??????б???????????????????????Push??????????????????????????push????????????????a1???????
????ImmutableStack<int> a1 = ImmutableStack<int>.Empty;
????a1.Push(10);
????//???????a1?????????push???????μ????
????a1 = a1.Push(10);
????//????????????????a1
????NET????????????
????ImmutableStack
????ImmutableQueue
????ImmutableList
????ImmutableHashSet
????ImmutableSortedSet
????ImmutableDictionary<K?? V>
????ImmutableSortedDictionary<K?? V>
????????伯????伯??????????????????