On the Haskell website, there’s this example quicksort implementation:
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
where
lesser = filter (< p) xs
greater = filter (>= p) xs
There is an explanation on the site, but I have a couple of questions that I didn’t see were addressed …
- where is the actual comparison/swap done on two elements for a re-order? Is this handled by the ‘Ord’ (ordered) type definition itself. So the type enforces this condition of being ordered?
- the ‘greater’ filter defines items ‘>= p’ (the pivot), so doesn’t this mean we’ll end up with an extra pivot [p] in resulting list of the function, due to the ‘++ [p]’ item?
What does
Ordmean?Ordjust means thatashould be comparable with itself or in stricter terms operations such as>,<, and==should be defined fora. You can think of it as a constraint on the method.So, where is the ordering done?
And the answer is the last pattern:
At run time, the program is going to get an array and the array must meet either of these two patterns:
Pattern 1#: It is empty, in which case the function returns that same empty array and stops.
Pattern 2#: It is not empty or in other words, there is a head element
pappended to a tailing arrayxs. In such a case, the function is told to putpin the middle, put all elements ofxsthat are less thanpon the left (as defined bylesser) ofpand all elements ofxsthat are greater than or equal topon the right ofp. Furthermore, the function is finally told to apply itself (i.e., the same functionquicksort) onlesser(which as we defined above, is the array on the left hand side ofp) andgreater(which as we defined above, is the array on the right hand side ofp). As you can see, this will go on till you are left with a zero sized array and pattern 1# terminates the function.Finally, whenever those recursive calls terminate the function shall return the array:
where
sortedlesseris the array that resulted from the application ofquicksortonlesserandsortedgreateris the array that resulted from the application ofquicksortongreater.Wait… are we not duplicating p again and again?
No, this is not how pattern matching works. It is saying all elements in
xsthat are greater than or equal top. By definitionpitself is out ofxs. If there are duplicates ofpinxsthen they will fall on the right hand side. Note that this choice will preserve the natural ordering of the original array.