Skip to content

Instantly share code, notes, and snippets.

@atomicules
Created April 11, 2011 23:35
Show Gist options
  • Save atomicules/914610 to your computer and use it in GitHub Desktop.
Save atomicules/914610 to your computer and use it in GitHub Desktop.
Selection Sort in Haskell the hard (but easier for me) way.
-- Selection Sort in Haskell
--
-- Cheating by using IORef for mutable variables since I don't know what I'm doing
-- with Haskell, although do have an inkling that the benefit of Haskell is that
-- all of below can be done in about three lines.
--
-- Assumes integer input only.
import Data.IORef
import Data.List.Split -- cabal install split
-- http://hackage.haskell.org/packages/archive/split/0.1.2.3/doc/html/Data-List-Split.html#v%3asplitOn
-- I'm not even going to think about doing this myself.
-- Used to get a comma delimted string as a list
main = do
-- Set up 'variables'
putStr "Enter List to Sort:"
stringinput <- getLine
let listinput = splitOn "," stringinput -- Convert comma delimited string to list
let intinput = [ read x :: Int | x <- listinput] --Convert list of strings to list of Integers
--Need to specify type http://learnyouahaskell.com/types-and-typeclasses
unsortlistIO <- newIORef intinput
elementIO <- newIORef []
sortlistIO <- newIORef []
sort unsortlistIO elementIO sortlistIO
sort unsortlistIO' elementIO' sortlistIO' = do
unsortlist <- (readIORef unsortlistIO')
sortlist <- (readIORef sortlistIO') -- initialise, for all intents and purposes
--print unsortlist --debug
if ((length unsortlist) > 0)
then do -- Note to self: Must remember to ident these after if!
-- find smallest element(s)
unsortlist <- (readIORef unsortlistIO')
writeIORef elementIO' (filter (==(minimum unsortlist)) unsortlist)
element <- readIORef elementIO'
-- Add to sorted list
sortlist <- readIORef sortlistIO'
writeIORef sortlistIO' (sortlist++element)
-- remove from original list
writeIORef unsortlistIO' (filter (not.(==(minimum unsortlist))) unsortlist)
readIORef sortlistIO'
--print sortlist --debug
sort unsortlistIO' elementIO' sortlistIO' -- loop. Ha!
else return sortlist -- Note to self: must be careful about returning the right type of thing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment