Skip to content

Instantly share code, notes, and snippets.

@huseyinyilmaz
Created July 16, 2016 05:37
Show Gist options
  • Save huseyinyilmaz/94cb4a14d30240eb1f2cf8fb01409c17 to your computer and use it in GitHub Desktop.
Save huseyinyilmaz/94cb4a14d30240eb1f2cf8fb01409c17 to your computer and use it in GitHub Desktop.
Return all permutations of given list
module Main where
-- inserts a to all possible places in list bs
-- insert 1 [2,3] -> [[1,2,3], [2,1,3], [2,3,1]]
insert :: t -> [t] -> [[t]]
insert a [] = [[a]]
insert a bs@(b:rest) = (a:bs):fmap (b:) (insert a rest)
-- Returns all permitations of given list
-- perms [1,2,3] -> [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
perms :: [t] -> [[t]]
perms [] = [[]]
perms (a:as) = [val |rest <- perms as, val <- insert a rest]
main :: IO ()
main = do
putStrLn ("Response:" ++ (show $ perms [1..3]))
-- Response:[[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment