Skip to content

Instantly share code, notes, and snippets.

@aruslan
Created February 9, 2012 23:39
Show Gist options
  • Save aruslan/1784289 to your computer and use it in GitHub Desktop.
Save aruslan/1784289 to your computer and use it in GitHub Desktop.
-- | The 'permutations' function returns the list of all permutations of the argument.
--
-- > permutations "abc" == ["abc","bac","cba","bca","cab","acb"]
permutations :: [a] -> [[a]]
permutations xs0 = xs0 : perms xs0 []
where
perms [] _ = []
perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)
where interleave xs r = let (_,zs) = interleave' id xs r in zs
interleave' _ [] r = (ts, r)
interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r
in (y:us, f (t:y:us) : zs)
main = print (permutations "abc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment