Skip to content

Instantly share code, notes, and snippets.

Created May 25, 2012 13:50
Show Gist options
  • Select an option

  • Save anonymous/2788261 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/2788261 to your computer and use it in GitHub Desktop.
Quicksort with reading from stdin
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