Created
July 3, 2010 14:27
-
-
Save nickrolfe/462607 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Compute all n! permutations of a list of n objects | |
-- | |
-- The algorithm is Method 1 from Knuth's The Art of Computer Programming | |
-- Volume 1, Chapter 1, Section 1.2.5 Permutations and Factorials. | |
-- Given an object x and a list of objects ys of length n, insert will return a | |
-- list of n+1 lists by inserting x in all posssible places in ys. | |
-- e.g. insert 1 [2,3,4] returns the following: | |
-- [[1,2,3,4], [2,1,3,4], [2,3,1,4], [2,3,4,1]] | |
insert :: a -> [a] -> [[a]] | |
insert x [] = [[x]] | |
insert x zs@(y:ys) = (x:zs) : map (y :) (insert x ys) | |
-- The base case is trivial. | |
-- The inductive case inserts the head of the list in every position (by | |
-- calling insert x) of all permutations of the tail. | |
perms :: [a] -> [[a]] | |
perms [] = [[]] | |
perms (x:xs) = concatMap (insert x) (perms xs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment