Created
May 25, 2012 13:50
-
-
Save anonymous/2788261 to your computer and use it in GitHub Desktop.
Quicksort with reading from stdin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| main :: IO () | |
| main = do | |
| putStrLn "Please enter a sequence of numbers to be sorted" | |
| putStrLn "Press ENTER twice to start sorting" | |
| nums <- getnums | |
| nums_s <- return $ sort nums | |
| putStrLn $ "Well, the sorted list is " ++ show nums_s | |
| return () | |
| sort :: (Ord a) => [a] -> [a] | |
| sort [] = [] | |
| sort (p:n) = | |
| sort smaller ++ [p] ++ sort larger | |
| where | |
| smaller = do | |
| x <- n | |
| True <- return (x < p) | |
| return x | |
| larger = do | |
| x <- n | |
| True <- return (x >= p) | |
| return x | |
| getnums :: (Num a, Read a) => IO [a] | |
| getnums = readnum >>= \mnum -> | |
| case mnum of | |
| Nothing -> return [] | |
| Just num -> getnums >>= \nums -> return (num:nums) | |
| readnum :: (Num a, Read a) => IO (Maybe a) | |
| readnum = readword >>= \word -> | |
| case word of | |
| [] -> return Nothing | |
| word -> return $ Just (read word) | |
| readword :: IO (String) | |
| readword = getChar >>= \char -> | |
| case char of | |
| '\n' -> return [] | |
| ' ' -> return [] | |
| chr -> readword >>= \chrs -> return (chr:chrs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment