public
Last active

C# vs ML

  • Download Gist
Language Dual
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
abstract class ListPair<T>
where T : IComparable<T>
{
static IEnumerable<T> empty = new T[0];
public abstract IEnumerable<T> Merge();
protected virtual LeftList Left { get; private set; }
protected virtual RightList Right { get; private set; }
 
public static ListPair<T> Create(LeftList left, RightList right)
{
foreach (var x in left)
foreach (var y in right)
return new BothNonEmpty () { Left = left, Right = right };
 
foreach (var x in left)
return OneEmpty.Create (left);
 
return OneEmpty.Create (right);
}
 
public abstract class TaggedList : IEnumerable<T>
{
IEnumerable<T> xs;
 
public TaggedList(IEnumerable<T> xs)
{
this.xs = xs;
}
 
public IEnumerator<T> GetEnumerator()
{
return xs.GetEnumerator ();
}
 
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator ();
}
}
 
public sealed class LeftList : TaggedList
{
public LeftList(IEnumerable<T> xs) : base (xs) { }
}
 
public sealed class RightList : TaggedList
{
public RightList(IEnumerable<T> xs) : base (xs) { }
}
 
sealed class BothNonEmpty : ListPair<T>
{
public override IEnumerable<T> Merge()
{
var fst = new[] { Left.First (), Right.First () };
var max = new[] { fst.Max () };
var min = new[] { fst.Min () };
 
var left = new LeftList(max.Concat (Left.Skip (1)));
var right = new RightList(Right.Skip (1));
var rest = ListPair<T>.Create (left, right).Merge ();
 
return min.Concat (rest);
}
}
 
abstract class OneEmpty : ListPair<T>
{
private IEnumerable<T> xs;
 
public static OneEmpty Create(LeftList xs)
{
return new _Left (xs);
}
 
public static OneEmpty Create(RightList xs)
{
return new _Right (xs);
}
sealed class _Left : OneEmpty
{
public _Left(LeftList xs) { this.xs = xs; }
protected override LeftList Left { get { return new LeftList (xs); } }
protected override RightList Right { get { return new RightList(empty); } }
}
 
sealed class _Right : OneEmpty
{
public _Right(RightList xs) { this.xs = xs; }
protected override LeftList Left { get { return new LeftList (empty); } }
protected override RightList Right { get { return new RightList (xs); } }
}
 
public sealed override IEnumerable<T> Merge()
{
return xs;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.