Long time, no blog post. Quite a few of my friends have
wasted no time in asking me if my blog is dead.
I’ve been trying to learn Haskell lately.
Found nothing to blog about, so I thought this might be interesting.
How would something I found on the haskell wiki translate to Python.
qsort :: (Ord a) => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort([ n | n <- xs , n < x ]) ++ [x] ++ qsort([ n | n <- xs , n >= x ])
Sreeram came up with this:
def qsort(l): if not l : return l return qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])
head = lambda x: x[0] tail = lambda x: x[1:] def qsort(l): return l if not l else qsort(filter(lambda x:x<head(l),tail(l))) + [head(l)] + qsort(filter(lambda x:x>=head(l),tail(l)))
Now for the fun part ![]()
Initially I made a naive mistake of defining head as
head = lambda x: x[1:]
I was thinking about avoiding IndexErrors, but I’d forgotten that the
function would never reach that condition, since “not l” will evaluate to True for an empty list
And also that head should return an element of the list, not a list
The interesting bit is, if head is defined so, the qsort function just ends up reversing the list.
Finally, I also found this
Quicksort in 3 Lines recipe on the Python Cookbook
PS: Couldn’t come up with a title for this post, I was almost tempted to use `Nothing`,
Finally decided to come up with something more inflamatory.
Anonymous on October 17th, 2006 at 10:39 AM says:
I would really be interested to see performance timings for these haskell and python quick sort implementations.
Anonymous on October 17th, 2006 at 2:13 PM says:
Am I missing something or is there a mistake in your post? The “naive” version looks the same as the real one.
Jeethu Rao on October 17th, 2006 at 5:23 PM says:
You’re right,
Here’s the ‘right’ naive version of head
head = lambda x: x[1:]
I’ve updated it.