Skip to content

Instantly share code, notes, and snippets.

@AloofBuddha
Created June 24, 2022 15:28
Show Gist options
  • Save AloofBuddha/f5777c9560636e2bd54a3b2f5f838c0d to your computer and use it in GitHub Desktop.
Save AloofBuddha/f5777c9560636e2bd54a3b2f5f838c0d to your computer and use it in GitHub Desktop.
import Data.List (inits, tails)
perms :: [a] -> [[a]]
perms [] = [[]]
perms (x : xs) = perms xs >>= spread x
where
spread :: a -> [a] -> [[a]]
spread el lst = zipWith (\x y -> x ++ [el] ++ y) (inits lst) (tails lst)
main :: IO ()
main = print $ perms [1, 2, 3]
-- evaluates to [[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