comparison between haskell and c++
Just thought I'd put this here. It's a quick comparison between equivalent pieces of Haskell and C++ code.
Haskell code:
qsort [] = []
qsort (x:xs) = qsort less ++ [x] ++ qsort more
where less = filter (<x) xs
more = filter (>=x) xs
C++ code:
template <typename T>
void qsort (T *result, T *list, int n)
{
if (n == 0) return;
T *smallerList, *largerList;
smallerList = new T[n];
largerList = new T[n];
T pivot = list[0];
int numSmaller=0, numLarger=0;
for (int i = 1; i < n; i++)
if (list[i] < pivot)
smallerList[numSmaller++] = list[i];
else
largerList[numLarger++] = list[i];
qsort(smallerList,smallerList,numSmaller);
qsort(largerList,largerList,numLarger);
int pos = 0;
for ( int i = 0; i < numSmaller; i++)
result[pos++] = smallerList[i];
result[pos++] = pivot;
for ( int i = 0; i < numLarger; i++)
result[pos++] = largerList[i];
delete [] smallerList;
delete [] largerList;
};
As you can see, the Haskell version is far shorter. It's also prettier and easier to understand.