I am starting to learn Haskell and I read this page on the Haskell wiki which reports on this qsort implementation:
qsort :: (Ord a) => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort less ++ [x] ++ qsort more where less = filter (<x) xs more = filter (>=x) xs
and then a warning that this is not the most efficient way to do this, and an article link that shows an incredibly detailed version of the same algorithm. Just by looking at it, I, although this is not what I studied Haskell, and I wanted to make a better version of the original qsort, without sacrificing my elegance. I mainly focused on eliminating the need to run filter twice every call, and this is what I came up with:
filter' :: (a -> Bool) -> [a] -> ([a], [a]) filter' _ [] = ([], []) filter' fa = filterInternal a ([], []) where filterInternal [] p = p filterInternal (x:xs) (l, t) | fx = filterInternal xs (x:l, t) | otherwise = filterInternal xs (l, x:t) qsort' :: (Ord a) => [a] -> [a] qsort' [] = [] qsort' (x:xs) = qsort' less ++ [x] ++ qsort' more where (more, less) = filter' (>x) xs
But I'm not sure if this is really better. I mean, it works, but how does it compare with the original version?
source share