Post by Jon Harropqsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
You cannot get much simpler, yet the state-of-the-art Haskell compiler still
runs it about 6,000x slower than most other languages precisely because
these optimizations all failed to pay off.
You certainly seem to be a big fan of lies, damn lies and statistics don't
you Jon?
The above qsort implementation is elegant but far from optimal. The
important thing however is that compiling that with GHC does not produce
a program significantly slower than than other compilers compiling the
same algorithm.
Here is a full (corrected) haskell test program:
import System.Random (randomRIO)
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (> x) xs)
randIntList :: Int -> Int -> IO [Int]
randIntList len maxint = do
list <- mapM (\_ -> randomRIO (0, maxint)) [1 .. len]
return list
main :: IO ()
main = do
list <- randIntList 1000000 1000000
let sorted = qsort list
-- For verification:
-- putStrLn $ show sorted
putStrLn $ show $ head sorted
and here is the Ocaml version of the *same* *algorithm* :
(* Need this to avoid stack overflows in the stdlib version. *)
open ExtList
let rec qsort lst =
match lst with
| [] -> []
| x :: xs ->
qsort (List.filter (fun y -> y < x) xs)
@ [x] @ qsort (List.filter (fun y -> y > x) xs)
let randIntList len maxint =
let rec builder accum count =
if count >= len then accum
else builder (Random.int maxint :: accum) (count + 1)
in
builder [] 0
let () =
let lst = randIntList 1000000 1000000 in
let sorted = qsort lst in
(* For verification only.
print_endline (String.concat "," (List.map string_of_int sorted)) ;
*)
print_int (List.hd sorted) ;
print_newline ()
Guess what, compiled as:
ocamlopt -I +extlib extLib.cmxa mlsort.ml -o mlsort
ghc -O2 --make hssort.hs -o hssort
they both take about 10 seconds to execute. Sometimes the Ocaml version wins
and sometimes the Haskell version wins.
Let me re-iterate, this algorithm is non-optimal in any language and
comparing Haskell compiling this algorithm against optimal algorithms
in other langauges shows you as the clown you are.
Erik
--
----------------------------------------------------------------------
Erik de Castro Lopo
http://www.mega-nerd.com/