Monday, August 20, 2007

Quicksort in Haskell Quicksort is a commonly used example of how succinct Haskell programming can be. It usually looks something likes this:
qsort :: (Ord a Bool) => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort (filter (<= x) xs) ++ [x] ++ qsort (filter (> x) xs)
The problem with this function is that it's not really Quicksort. Viewed through sufficently blurry glasses (or high abstraction altitude) it's looks like the real Quicksort. What they have in common is overall algorithm: pick a pivot (always the first element), then recursively sort the ones that are smaller, the ones that are bigger, and then stick it all together. But in my opinion the real Quicksort has to be imperative because it relies on destructive update; and it uses a very elegant partitioning algorithm. The partitioning works like this: scan from the left for an element bigger than the pivot, then scan from the right for an element smaller than the pivot, and then swap them. Repeat this until the array has been partitioned. Haskell has a variety of array types with destructive updates (in different monads), so it's perfectly possible to write the imperative Quicksort in Haskell. To make the code look reasonably nice I'm going to use my C-like DSEL to write the code. Here it is:
qsortM :: forall i a m r arr .
         (MonadRef m r, Num i, Ix i, MArray arr a m, Ord a Bool) =>
         arr i a -> m (arr i a)
qsortM ma = runE $ do
    (lb, ub) <- embed $ getBounds ma
    let mlb = pure0 lb
        mub = pure0 ub
    a <- liftArray ma

    let qsort' l r =
            if1 (r > l) $ do
                i <- auto l
                j <- auto (r+1)
                let v = a[l] :: E m a
                    iLTj = i < (j :: E m i)
                while iLTj $ do
                    while ((i += 1) < mub && a[i] < v)
                        skip
                    while (a[j -= 1] > v)
                        skip
                    if1 iLTj $ do
                        a[i] =:= a[j]
                a[l] =:= a[j]
                qsort' l (j-1)
                qsort' i r

    qsort' mlb mub
    return ma
So the type is arr i a -> m (arr i a), i.e., qsortM takes an array indexed with i and elements of type a. It returns the sorted array, but the sorting takes places in some monad m. And then there are all kinds of constraints on the type variables. The MonadRef m r says that the monad has to have references so we can have some variables. The array index has to be in the Ix; that's part of the general array constraints. It also have to be numeric so we can add and subtract indicies. The array type has to fulfill MArray arr a m which means that arr is an array of a and updatable in monad m. Finally, the elements have to be ordered. I'm not using the normal Ord class, but instead an overloaded Ord where the return type is overloaded too. A few comments on the code. The liftArray function lifts a regular array into one that can be indexed with [i]. The =:= operator swaps two variables. The skip function does nothing. In traditional C style we do all the side effects while computing the condition. There are some type signatures in the code that are annoying, but that I have not found a way around yet. But otherwise, the code proceeds like most any imperative Quicksort. The i and j variables scan the array from left and right to locate two elements that need swapping. We then swap them, and continue scanning until the indicies cross. After the partitioning we swap the pivot into place and sort the two parts recursively. So, this function is polymorphic in the monad. But there is one monad that I think is extra interesting, namely ST. With this monad you can do references, updatable arrays, etc., and finally you can seal it all of with runST. The resulting type is pure and shows no signs of what happened inside. This is a really amazing feat, in my opinion. The type checker performs the proof that nothing about the "dirty" innards leaks out. So instead of some informal reasoning that a function with an impure inside can be pure on the outside you have a machine checked proof. Of course, there's a meta proof that this is all correct, but John Launchbury and Simon Peyton Jones have already done that once, and now we just need the type checker. Here's the code:
qsortA :: forall i a . (Num i, Ix i, Ord a Bool) => Array i a -> Array i a
qsortA a = runSTArray sa
  where sa :: ST s (STArray s i a)
        sa = thaw a >>= qsortM
We're using runSTArray instead of runST, because it provides an efficient way to turn a mutable array on the inside into an immutable array on the outside. The thaw function turns an immutable array into a mutable one, but it has to make a copy to be safe, since we don't want to mutate the original. Finally, if we want to sort lists we can always convert back and forth.
asList :: (Array Int a -> Array Int a) -> ([a] -> [a])
asList f xs = elems . f . listArray (1, length xs) $ xs 

qsort :: (Prelude.Ord a) => [a] -> [a]
qsort = asList qsortA
The final qsort has the normal type signature (I switched to the normal Ord again).

Labels:

36 Comments:

Blogger Paul Johnson said...

Interesting. I've sometimes thought of doing a shuffle function like this, since O(n) shuffling as described by Knuth also needs a constant time swap item operation. Oleg has described a functional shuffle algorithm, but its O(n * log n)

On the other hand I wonder if you couldn't do swapping in some wierd zipper structure. I'll think about it.

11:30 PM  
Blogger jsnx said...

Thanks for posting -- I'll definitely be looking at this again as I learn more Haskell.

9:14 PM  
Blogger namekuseijin said...

wonderful! You've made Haskell into C!

I thought the whole point of using high level languages was to favor and focus on higher level abstractions and get away from low level details and mechanics. You've just brought it all into your version: state, lots of verbose low-level machinery and imperative thinkage...

look: if you want C, you know where to get it. Let's not fill Haskell code with lots of monads and verbosity just for the sake of it, right?

3:10 AM  
Blogger GameOn said...

namekuseijin: Whilst I appreciate what you're saying I firmly believe that if you can save such a large amount of memory, do so.

paul johnson: thanks for the tip about an O(n) shuffle, I'll have a look at it.

Blog Author: Thanks for such an informative article on the 'proper' quicksort.

1:11 AM  
Blogger Parch said...

Thanks for posting this code. Only yesterday I was wondering what quicksort in an 'elegant' language (e.g. lisp) would look like. I tried it, and quickly realized making things as efficient as C wasn't so simple. I remembered that Haskell had the 'shortest' quicksort definition of nearly any language, then wondered what an efficient haskell version would look like... and now thanks to haskellwiki, here I am. :)

5:49 AM  
Blogger dghnfgj said...

Three passions,warcraft leveling simple but wow lvl overwhelmingly strong,wow power level have governed wow power level my life: the longing wrath of the lich king power leveling for love, the search for knowledge,World of warcraft Power Leveling and unbearable pity WOTLK Power Leveling for the suffering wlk power leveling of mankind. These passions,wlk power leveling like great winds,age of conan gold have blown me hither and thither,cheap aoc gold in a wayward course,aoc power leveling over a great ocean ffxi gil of anguish, reaching final fantasy xi gil to the very verge of despair. I have sought love, first, because it brings ecstasy - ecstasy so great that I would often have sacrificed FFXI Gil all the rest of life for final fantasy gil a few hours of this joy. I have sought it, wow gold because it relieves loneliness--that terrible loneliness in which one shivering consciousness dog clothes looks over the rim of the world into the cold unfathomable lifeless abyss.

8:51 AM  
Blogger dsfgsdfgsdfgds said...

看房子,買房子,建商自售,自售,台北新成屋,台北豪宅,新成屋,豪宅,美髮儀器,美髮,儀器,髮型,EMBA,MBA,學位,EMBA,專業認證,認證課程,博士學位,DBA,PHD,在職進修,碩士學位,推廣教育,DBA,進修課程,碩士學位,網路廣告,關鍵字廣告,關鍵字,課程介紹,學分班,文憑,牛樟芝,段木,牛樟菇,日式料理, 台北居酒屋,日本料理,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,住宿,訂房,HOTEL,飯店,造型系列,學位,牛樟芝,腦磷脂,磷脂絲胺酸,SEO,婚宴,捷運,學區,美髮,儀器,髮型,牛樟芝,腦磷脂,磷脂絲胺酸,看房子,買房子,建商自售,自售,房子,捷運,學區,台北新成屋,台北豪宅,新成屋,豪宅,學位,碩士學位,進修,在職進修, 課程,教育,學位,證照,mba,文憑,學分班,網路廣告,關鍵字廣告,關鍵字,SEO,关键词,网络广告,关键词广告,SEO,关键词,网络广告,关键词广告,SEO,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,住宿,訂房,HOTEL,飯店,婚宴,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,住宿,訂房,HOTEL,飯店,婚宴,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,住宿,訂房,HOTEL,飯店,婚宴,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,居酒屋,燒烤,美髮,儀器,髮型,美髮,儀器,髮型,美髮,儀器,髮型,美髮,儀器,髮型,小套房,小套房,進修,在職進修,留學,證照,MBA,EMBA,留學,MBA,EMBA,留學,進修,在職進修,牛樟芝,段木,牛樟菇,關鍵字排名,網路行銷,关键词排名,网络营销,網路行銷,關鍵字排名,关键词排名,网络营销,PMP,在職專班,研究所在職專班,碩士在職專班,PMP,證照,在職專班,研究所在職專班,碩士在職專班,SEO,廣告,關鍵字,關鍵字排名,網路行銷,網頁設計,網站設計,網站排名,搜尋引擎,網路廣告,SEO,廣告,關鍵字,關鍵字排名,網路行銷,網頁設計,網站設計,網站排名,搜尋引擎,網路廣告,SEO,廣告,關鍵字,關鍵字排名,網路行銷,網頁設計,網站設計,網站排名,搜尋引擎,網路廣告,SEO,廣告,關鍵字,關鍵字排名,網路行銷,網頁設計,網站設計,網站排名,搜尋引擎,網路廣告,EMBA,MBA,PMP
,在職進修,專案管理,出國留學,EMBA,MBA,PMP
,在職進修,專案管理,出國留學,EMBA,MBA,PMP
,在職進修,專案管理,出國留學

住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,住宿,民宿,飯店,旅遊,美容,美髮,整形,造型,設計,室內設計,裝潢,房地產,進修,在職進修,MBA,EMBA,羅志祥,周杰倫,五月天,蔡依林,林志玲,羅志祥,周杰倫,五月天,蔡依林,林志玲,羅志祥,周杰倫,五月天,蔡依林,羅志祥,周杰倫,五月天,蔡依林

6:49 AM  
Blogger yanhui said...

How to get more Anarchy credits. He gave me some Anarchy Online credits, he said that I could buy AO credits, but I did not have money, then I played it all my spare time. From then on, I got some Anarchy gold, if I did not continue to play it, I can sell Anarchy online gold to anyone who want.

To every game player angels gold is very import. My friend gave me some angels online gold, he said that I could buy angels gold, but I did not have money, then I played it all my spare time. From then on, I got some cheap angels online gold.

4:57 AM  
Blogger nasha said...

Why was there no follow on bankruptcy then? The bailout of AIG FP went to (wow power leveling) hedge funds that bound credit swaps on Lehman failing or others betting on rating (wow power leveling) declines. AIG has drained over 100 billion from the government. Which had to go to (wow power leveling) those who bet on failures and downgrades. Many of whom (power leveling)were hedge funds. I-banks that had offsetting swaps needed the money from the AIG bailout or they would have been caught. Its an (wow powerleveling) insiders game and it takes just a little bit too much time for most people to think (wow gold) through where the AIG 100 billion bailout money went to, hedge funds and players, many of whom hire from the top ranks of DOJ, Fed, Treasury, etc. ZHANG XIAO CHEN

6:07 AM  
Blogger xuemei said...

I like play online game, I also buy ragnarok online zeny and ro zeny, the ragnarok zeny is very cheap, and use the iro zeny can buy many things, I like cheap zeny, thanks, it is very good.

I like play online game, I also buy rupees and rappelz rupees, the rappelz gold is very cheap, and use the rappelz money can buy many things, I like cheap rappelz rupees, thanks, it is very good.

1:57 AM  
Blogger kiloi said...

puma shoes
chaussures pumacheap polos
polo shirts
ralph lauren polo shirtssport shoes
ugg boots
mp4
trade chinalacoste polo shirts
chaussure puma femmewedding dressestennis racket
cheap handbags
HAIR STRAIGHTENERS

2:02 PM  
Blogger kiloi said...

nike tnEnter the necessary language
translation, up to 200 bytes winter, moves frequently in Chinanike chaussures showing that the deep strategy of the Chinese market. Harvard Business School, tn chaussures according to the relevant survey data show that in recent years the Chinese market three brands, Adidas, Li Ning market share at 21 percent, respectively,

2:02 PM  
Blogger kiloi said...

mens clothing men's sweate, cheap columbia jackets, lacoste sweater, ralph lauren polo shirts,ski clothing. Free Shipping, PayPal Payment. Enjoy your shopping experience on mensclothingstore.us

2:02 PM  
Blogger miyuki said...

ralph Lauren polo shirts , Lacoste Polo Shirts, Burberry Polo Shirts.wholesale Lacoste polo shirts and polo ralph laurenwith great price. clothingol.com offers lot of 10 lacoste polo shirts and lot of 20 cheap polo shirts. clothingol.com offers classic fit polo shirts. polo clothingnike air max ltd is divided into sports life and NIKE NIKENIKE air shoes sports mark for a big hook (swoosh)NIKE life (NSW) mark is a hook NIKE swoosh (English) +Sometimes life will sell NIKE sports channel,cheap puma mens shoes , enjoy shopping!

3:50 AM  
Blogger miyuki said...

Cheap Brand Jeans ShopMen Jeans - True Religion Jeans, Women JeansGUCCI Jeans, Levi's Jeans, D&G Jeans, RED MONKEY Jeans, Cheap JeansArmani Jeans, Diesel Jeans, Ed hardy Jeans, Evisu Jeans, Jack&Jones Jeans...

4:25 AM  
Blogger nike said...

Lacoste polo shirts
north face jackets
cheap handbags
cheap purse
women's nike shoes

7:41 AM  
Blogger sky22d said...

In a womens clothing boutique store, several girls were trying on fashionable new polos men poloswomen polos. In addition to flower dresspolo fashionembroodered polostennis racketsclothing poloclothingedhardyshirtedhardyclothingedhardysummer ed hardy clothingcheap shirtsed hardy brandcheap ed hardypolo shirts cheapcheap tennis racketsdiscount tennis racketsralphlaurenpoloshirtscheappolospolo fashion, flower shirt, flower jacket, even with the scarf pattern is all kinds of flowers.

6:57 AM  
Blogger sky22d said...

This issue ed hardy t-shirts is of paramount importance as forensic experts ed hardy mens claimed to have discovered in the collar of one of ed hardy womens the fragment of an electronic timer which provided the key link ed hardy sunglasses between the bombing and Libya.They will surely love polo ralph laurenlike this. The styles are so fabulous burberry polos catching the light who would not love lacoste polo shirts like these.

6:59 AM  
Blogger sky22d said...

Advanced precision comes from the connection of the Side prince-o3-tour to the cheap tennis racquets at three o'clock and nine o'clock, which results in less torque (or twisting) at polo logopolo shirts in voguepolo women clothinged-hardy shirtsed-hardy sunglassesimpact.

7:00 AM  
Blogger qwee2232 said...

It was just a ed hardy clothing with a colourful design of three wolves howling at the moon. Now, it’s a viral sensation with its own ed hardy clothes, videos and an exploding following that has swamped a tiny New ed hardy shirts. Longer arms extend the yoke farther up each side of the babolat pure drive. These arms - or Side Drivers wilson k six- create a stiffer construction and distribute maximum power from the base of the yoke to the middle of the head microgel.

7:08 AM  
Blogger qwee2232 said...

discount ralph lauren polos are one of the highest in demand cheappolos because along with protecting your skin it also enhances your looks. These polo clothingare the in-thing in today's ralph lauren polo shirts fashion world and among the youngstersdiscount polossummer polospolo shirts whosale.

7:11 AM  
Blogger qwee2232 said...

For the polo shirts, many people loveralphlaurenpoloshirtscheappolos but hate it. This brand is favorite, products like his style; the same is hard not to develop the Lacoste polo shirts brand has been cheap lacoste polos the Asian market. There are stores to buy wholesale polo shirts, However, ralph lauren polo shirts is too many fakes. It will be out of shape cheap ralph lauren polos.

7:14 AM  
Blogger j said...

Modern tennis racquet in the manufacturing sector have been in use for close to the aerospace industry and military-industrial material products. Over the past two decades, metal materials and chemical materials to upgrade the high level of tennis racket manufacturer has laid a solid foundation. In today's big brands have more than tennis: Head junior tennis racket,Wilson tennis racquet, Wilson tennis racket,Head tennis racket,Babolat tennis racket......
ed hardy clothing
ed hardy clothes
ed hardy shirts
ed hardy t-shirts
ed hardy sunglasses
ed hardy mens
ed hardy womens
Wholesale Handbags
Cheap Handbags
Womens Handbags
Cheap Purses
Designer Handbags

10:19 AM  
Blogger j said...

Ralph Lauren Polo is the most famous sports shirt.Burberry Polo Shirt is the most well-known in France jerseys. The north face jacket is a winter essential goods.Columbia jacket and spyder jacket let people have more choice of clothes. Different brands have different design styles, but all it attracts us.
cheap tennis racquet
tennis racquet discount
cheap tennis racket
discount Tennis Racket

10:19 AM  
Blogger polo shirt said...

God bless you!I really agree with your opinions.Also,there are some new fashion things here,gillette razor blades.gillette mach3 razor bladesfor men.As for ladies,gillette venus razor blades must the best gift for you in summer,gillette fusion blades are all the best choice for you.

4:23 AM  
Blogger polo shirt said...

fantastic!God bless you!Meanwhile,you can visit my China Wholesale,we have the highest quality but the lowest price fashion products wholesale from China.Here are the most popular China Wholesale products for all of you.Also the polo clothing is a great choice for you.

4:23 AM  
Blogger polo shirt said...

fantastic!God bless you!Meanwhile,you can visit my China Wholesale,we have the highest quality but the lowest price fashion products wholesale from China.Here are the most popular China Wholesale products for all of you.Also the polo clothing is a great choice for you.

4:24 AM  
Blogger polo shirt said...

Wonderful!You can find the father who desire fashionable eg,uggs fashion,you can enjoy uggs online here, intellectual polo shirt simultaneously.

4:25 AM  
Blogger polo shirt said...

Do not mean bad.Thank you so much!Men's polo shirts was the shirt of choice for diverse groups of teenagers.Brightly coloured polo shirts can make you look like a Day-glo dirigible.

4:25 AM  
Blogger polo shirt said...

Perfect!!You are a outstanding person!Have you ever wore chaussures puma, puma CAT,Puma shoes store gives some preview of puma speed cat,puma basket, puma speed, puma speed and other puma shoes. These puma sport items are at store recently and available for anyone.

4:26 AM  
Blogger polo shirt said...

Wonderful!!You can find the father who desire fashionable, intellectual cheap polos simultaneously, you can find a psychologist to study the most harmonious of families should be pink mens clothing, so do not want to take the mature route for the father, buy cheap polos, the learn from such a walk in between the formal and casual styling, refined style to create a sense of mild authority.

4:26 AM  
Blogger polo shirt said...

Awesome!!!Best wishes for you !!wholesale polo shirts is the father of the summer should be prepared to most commonly used item, it has both style and shape of polo clothing, and vest with a random function, so that in the short-sleeved apply to both on many occasions, the pink and black color men's polo shirts brought into effect, lightweight cotton, linen texture to demonstrate masculine temperament and sense of fashion exhaustively. polo shirts for sale

4:26 AM  
Blogger polo shirt said...

Thank you so much!!polo shirt men'ssweate,cheap polo shirts cheap columbia jackets, lacoste sweater, ralph lauren polo shirts,ski clothing. Free Shipping, PayPal Payment. Enjoy your shopping experience on mensclothingus.com.We have mens polo shirts.

4:27 AM  
Blogger haitao said...

1)
cheap hair straighteners
chi hair straightener
chi flat iron

new polo shirts
cheap Lacoste polo shirts
cheap Lacoste polo shirts

cheap handbags
cheap bags
puma chaussures
chaussures puma
chaussure puma

Men's North Face
Women's North Face


hair straighteners
sexy lingerie store
cheap ugg boots
tattoo wholesale
men's clothing
women's clothing


2009 nike shoes
new nike shoes
Women's max
Men's max 93
nike shox
Nike air force
Nike air max 2003
nike air max ltd
nike air max tn
Nike air rift
Nike air Yeezy
nike airmax
Nike air max 90
Nike air max 97
nike birds nest shoes
nike dunk
nike RT1 shoes
nike SB
nike shox shoes
Nike shox OZ shoes
Nike shox R2 shoes
Nike shox R3 shoes
Nike shox R4 shoes
Nike shox R5 shoes
Nike shox TL3
nike trainers lovers

tennis rackets
Wilson tennis rackets
HEAD tennis rackets
Babolat tennis rackets

5:20 AM  
Blogger J&amp;D said...

視訊|影音視訊聊天室|視訊聊天室|視訊交友|視訊聊天|視訊美女|視訊辣妹|免費視訊聊天室

自慰器|自慰器

網頁設計|網頁設計公司|最新消息|訪客留言|網站導覽

免費視訊聊天|辣妹視訊|視訊交友網|美女視訊|視訊交友|視訊交友90739|成人聊天室|視訊聊天室|視訊聊天|視訊聊天室|情色視訊|情人視訊網|視訊美女
一葉情貼圖片區|免費視訊聊天室|免費視訊|ut聊天室|聊天室|豆豆聊天室|尋夢園聊天室|聊天室尋夢園|影音視訊聊天室||

9:56 AM  
Blogger Kevin said...

牙醫,植牙,矯正,紋身,刺青,創業,批發,皮膚科,痘痘,中醫,飛梭雷射,毛孔粗大,醫學美容,seo,關鍵字行銷,關鍵字自然排序,網路行銷,關鍵字自然排序,關鍵字行銷seo,關鍵字廣告,部落格行銷,網路行銷,seo,關鍵字行銷,關鍵字廣告,關鍵字,自然排序,部落格行銷,網路行銷,網路爆紅,牛舌餅婚紗台中婚紗,腳臭,腳臭,腳臭,腳臭,腳臭,腳臭,腳臭,中古車,二手車,中古車,二手車,高雄婚紗,搬家,搬家公司,服飾批發,團體服,街舞,融資,借貸,借錢,小產,雞精

9:03 AM  

Post a Comment

<< Home