Skip to content

Instantly share code, notes, and snippets.

@jutememo
Created April 25, 2011 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jutememo/940268 to your computer and use it in GitHub Desktop.
Save jutememo/940268 to your computer and use it in GitHub Desktop.
import Control.Monad.State
type Ary a = [a]
type Temp a = a
type Vars a = (Ary a, Temp a)
toTemp :: Int -> State (Vars a) ()
toTemp i = modify $ \(xs, tmp) -> (xs, xs!!i)
copyElem :: Int -> Int -> State (Vars a) ()
copyElem i j = modify $ \(xs, tmp) ->
(take i xs ++ xs!!j : drop (i+1) xs, tmp)
fromTemp :: Int -> State (Vars a) ()
fromTemp j = modify $ \(xs, tmp) ->
(take j xs ++ tmp : drop (j+1) xs, tmp)
swapS :: Int -> Int -> State (Vars a) ()
swapS i j = toTemp i >> copyElem i j >> fromTemp j
swap i j xs = fst $ execState (swapS i j) (xs, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment