Jafar Husain writes about the prettiness of F#’s type inference, but what I really liked in his post was his C# 3.0 implementation for Quick Sort:
1 public static IEnumerable<T> QuickSort<T>(this IEnumerable<T> list) 2 where T : IComparable 3 { 4 if (!list.Any()) 5 { 6 return Enumerable.Empty<T>(); 7 } 8 var pivot = list.First(); 9 var smaller = list.Where(item => item.CompareTo(pivot) <= 0).QuickSort(); 10 var larger = list.Where(item => item.CompareTo(pivot) > 0).QuickSort(); 11 12 return smaller.Concat(new[]{pivot}).Concat(larger); 13 }
Yes, the F# implementation is more concise, but Jafar really reminded how concise can C# be as well. When I first heard about C# 3.0’s var keyword, I belonged to the group that worried about code getting unreadable. Now I’ve grown to realize that type information can be over-rated. Sometimes it is just irrelevant noise.
Yeah, let’s not pull in a two-liner Python of Haskell version, though… Hehe.
It should be noted that this is not (really) quicksort.
See http://augustss.blogspot.com/2007/08/quicksort-in-haskell-quicksort-is.html
ps. he updated the code to prevent an infinite recursion..
Hi,
This is just awesome !
I love concise code with just enough recursion to make things done !
Grats.
Слабо моё имя расшифровать 5f7ce4443ca3a1ac3e669bda9276122e ?
>>”Yeah, let’s not pull in a two-liner Python of Haskell version, though… Hehe.”
nothing stop anyone to rewrite this into one string:
public static IEnumerable shortQuickSort (this IEnumerable list) where T : IComparable ():list.Skip(1).Where(item => item.CompareTo(list.First()) < = 0).qSort().Concat(new[] { list.First() }).Concat(list.Skip(1).Where(item => item.CompareTo(list.First()) > 0).qSort());
{
return !list.Any()?Enumerable.Empty
}