Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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