It's not a question (however see bottom of the post). Just for fun - just I trained with new C# features.
Haskell vs C# 8.0 :)
static class CS8_Tests
{
public static void Deconstruct<T>(this IEnumerable<T> items, out T head, out IEnumerable<T> tail)
=> (head, tail) = (items.FirstOrDefault(), items.Skip(1));
/// <summary>
/// Famous Haskell implementation:
/// quicksort :: (Ord a) => [a] –> [a]
/// quicksort[] = []
/// quicksort(x:xs) =
/// let smallerSorted = quicksort[a | a <– xs, a <= x]
/// biggerSorted = quicksort[a | a <– xs, a > x]
/// in smallerSorted ++ [x] ++ biggerSorted
/// </summary>
static IEnumerable<T> quickSort<T>(IEnumerable<T> items) where T : IComparable<T>
=> items switch
{
_ when items.Count() == 0 => items,
(var x, var xs) => quickSort(xs.Where(a => a.CompareTo(x) <= 0))
.Append(x)
.Concat(quickSort(xs.Where(a => a.CompareTo(x) > 0)))
};
static int indexOf<T>(IEnumerable<T> items, T target, int index = 0) where T : IEquatable<T>
=> items switch
{
(var h, _) when h.Equals(target) => index,
(_, var tail) when tail.Count() == 0 => -1,
(_, var tail) => indexOf(tail, target, index + 1),
};
public static void RunTests()
{
var items = new List<int> { 2, 5, 7, 5, 1, 4, 3, 1 };
var sorted_items = quickSort(items).ToList();
var index = indexOf(items, 1);
}
//public static IEnumerable<T> operator +(IEnumerable<T> elms1, IEnumerable<T> elms2)
// => elms1.Concat(elms2);
}
Unfortunately, we cannot define "+" operator for IEnumerable - then this code would be more compact (see commented lines at the bottom of the code).
It is interesting - why? - this may be my question.