I am starting to learn Haskell and I've been reading this page on Haskell's wiki, which reports 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
followed by a warning that this is not the most efficient way to do it, and linking an article which shows an incredibly verbose version of the same algorithm. Just by looking at it, I though that that was not what I was learning Haskell for, and I wanted to make a better version of the initial qsort without sacrificing its elegance. I mostly concentrated on eliminating the need to run filter
twice every call, and this is what I've come up:
filter' :: (a -> Bool) -> [a] -> ([a], [a])
filter' _ [] = ([], [])
filter' f a = filterInternal a ([], [])
where
filterInternal [] p = p
filterInternal (x:xs) (l, t)
| f x = 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 am not sure this is really better. I mean, it works, but how does it compare to the initial version?