Skip to content

Instantly share code, notes, and snippets.

@xiaohanyu
Created March 3, 2017 16:14
Show Gist options
  • Save xiaohanyu/44048f5ecf03016fdf468b956c6dfc6a to your computer and use it in GitHub Desktop.
Save xiaohanyu/44048f5ecf03016fdf468b956c6dfc6a to your computer and use it in GitHub Desktop.
Haskell permutation generation algorithm with list comprehension.
import Data.List
perm :: (Eq a) => [a] -> Int -> [[a]]
perm _ 0 = [[]]
perm xs r | length xs < r = [[]]
| otherwise = [x:ys | x <- xs, ys <- perm (delete x xs) (r - 1)]
@readams256
Copy link

readams256 commented Apr 13, 2020

Your Haskell implementation is brilliant!!! It is similar to the nPn Haskell version at https://stackoverflow.com/questions/49280797/permutation-algorithm-in-haskell
namely,

import Data.List ((\\),delete)

perms [] = [[]]
perms p = [x:xs | x <- p, xs <- perms (delete x p) ]

main = print $ perms [1,2,3]

However, yours is nPr or P(n,r), i.e., "n choose r", which is more general. I have been working on such an algorithm for a while. Do you have any suggestions regarding how you arrived at your solution/implementation?

Thank you.

Richard E. Adams
Email: readams256@gmail.com

@xiaohanyu
Copy link
Author

Hi, @readamd256,

To be honest, I forgot how I came up with this code snippets. But I think this gist is just a step of generalisation of your code.

@readams256
Copy link

Thank you!

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