A world beyond C++ (and Java) - my enthusiasm for functional programming:

Quick Sort - the famous algorithm invented by Antony Charles Hoare - is an example of intriguing simplicity.
What about a programming language with the power to describe this algorithm in two lines?

To begin with, the two lines of Haskell code:

  1. qSort [] = []
  2. qSort (x:xs) = qSort [z | z <-xs, z <= x] ++ [x] ++ qSort [z | z <- xs, z > x]


But what does this mean?

[ a b c ] is a list of elements a, b, and c, and [ ] is a list without any element. 
Thus, line 1 says nothing more than: and empty list sorted is an empty list; just as a rose is a rose is a rose.
However, because of the recursive nature of the following line, this is neither stupid nor trivial.

To understand line 2, we have to know the following notational conventions:

a:tail refers to a list [ a b c ... ] with the first element a followed by list tail = [ b c ... ].
The meaning of [ xpredicate ] is: a list formed of x for which predicate is a true statement.
And z <- xs is an awkward notation for z xs.
A comma inside a predicate means logical AND
: z <- xs
,  z > x stands for z xs AND z > x

With operator ++ we concatenate two lists: [ a b ] ++ [ c d e ] = [ a b c d e ].

Keeping this in mind, line 2 is not too difficult to read:
To sort a list (according to Hoare's algorithm) we have to

Two lines are sufficient to describe the quick sort algorithm!!
If you are familiar with the power of recursion, this will be not so much of a surprise for you.
However, you may agree: there is elegance in this concise description.


Until now, we did not say a word about the types of elements we are able to sort.
Let us load this two-line program into the Haskell interpreter Hugs and invoke qSort:

Obviously, our qSort is not restricted to a particular type of list elements. 
However, invoking

    qSort [ 42, "gamma" ]

will result in an error.

qSort can work on a list if

There is some similarity with a template in C++, but where is the type parameter?.
The Haskell interpreter or compiler is able to infer data types. We have not to specify type information explicitely.
But we can. Let us add one more line of Haskell code

    0.  qSort :: Ord e => [ e ] -> [ e ]

which is saying: the input as well as the output of qSort is a list of elements e. And these elements have a common property, described by class Ord.
The meaning of "class" is rather different from C++, it is something like an "interface", because it states that all types belonging to a class define a certain set of operations. Here, class Ord guarantees the existence of <=, >, and some other operators.

If you are writing Haskell code, you always do generic programming.


qSort :: Ord e => [ e ] -> [ e ]
qSort [] = []
qSort (x:xs) = qSort [z | z <-xs, z <= x] ++ [x] ++ qSort [z | z <- xs, z > x]

That way of programming is far beyond C++, Java, Pascal ...!