Skip to content

Instantly share code, notes, and snippets.

@jadlr
Last active February 20, 2016 23:09
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 jadlr/2022c3b1821216ee2847 to your computer and use it in GitHub Desktop.
Save jadlr/2022c3b1821216ee2847 to your computer and use it in GitHub Desktop.
Permutations of a certain length of a list
module ListPermutations where
listPermutations :: Integer => [a] -> b -> [[a]]
listPermutations l n = snd $ permutate l n
where permutate :: Integer => [a] -> b -> ([[a]], [[a]])
permutate [] _ = ([[]], [])
permutate (x:xs) n = let (pt, acc) = permutate xs n in permutateInner x pt pt acc n
where permutateInner :: Integer => a -> [[a]] -> [[a]] -> [[a]] -> b -> ([[a]], [[a]])
permutateInner _ [] pt acc _ = (pt, acc)
permutateInner h (x:xs) pt acc n
| (fromIntegral $ length x) /= n - 1 = permutateInner h xs ((h:x):pt) acc n
| otherwise = permutateInner h xs ((h:x):pt) ((h:x):acc) n
@jadlr
Copy link
Author

jadlr commented Feb 16, 2016

usage:

*ListPermutations> listPermutations [1,2,3] 2
[[1,3],[1,2],[2,3]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment