I have to write a Haskell function that gives all possible permutations of a given list.
The type signature has to be:
permutations :: [a] -> [[a]] For example, an acceptable result is (under ghci):
λ> λ> permutations [1,2,3] [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]] λ> The following restrictions apply:
- Plain lists are the sole authorized data structure, so no
SetorVector. - The permutations may be produced in any order.
- The function must work for any element type, i.e. no
Ord aorEq ainstances. - Only library functions from the standard Prelude may be used.
Does anyone know how I could do it ?
nextPermutation :: [Int] -> Maybe [Int]building block, you might be able to come up with a recursive version of yourpermutationsfunction.spreadfunction. Expressionspread 4 [1,2,3]puts 4 at all possible positions within [1,2;3] :[[4,1,2,3],[1,4,2,3],[1,2,4,3],[1,2,3,4]]. To get all permutations of [1,2,3,4], you just need to usespread 4on all permutations of [1,2,3]. So you have a base case:permutations [] = [[]]and a compound case:permutations (x:xs) = concat (map (spread x) (permutations xs)). And it is not that difficult to write a recursive implementation of functionspread.