Skip to content

Instantly share code, notes, and snippets.

@danslapman
Last active December 9, 2015 09:11
Show Gist options
  • Save danslapman/e140c6d7faada640f295 to your computer and use it in GitHub Desktop.
Save danslapman/e140c6d7faada640f295 to your computer and use it in GitHub Desktop.
Immutable Linked List
using System.Collections;
using System.Collections.Generic;
namespace Immutable
{
public sealed class LList<T> : IReadOnlyCollection<T>
{
public T Head { get; }
public LList<T> Tail { get; }
public bool IsEmpty { get; }
public int Count { get; }
public static LList<T> Empty { get; } = new LList<T>();
private LList()
{
Count = 0;
IsEmpty = true;
}
private LList(T head, LList<T> tail)
{
Head = head;
Tail = tail;
Count = tail.Count + 1;
}
public LList<T> Add(T value) => new LList<T>(value, this);
public IEnumerator<T> GetEnumerator()
{
if (!IsEmpty && Head != null)
yield return Head;
var rest = Tail;
while (rest != null && !rest.IsEmpty)
{
yield return rest.Head;
rest = rest.Tail;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public static class LList
{
public static LList<T> Cons<T>(T value, LList<T> list) => list.Add(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment