List of all 4 possible choices out of 9 in Haskell

I cannot find an effective way to select all permutations of 4 elements from a list of 9 elements in Haskell. The python way to do the same:

itertools.permutations(range(9+1),4) 

Ineffective way to do this in Haskell:

 nub . (map (take 4)) . permutations $ [1..9] 

I would like to find something like:

 permutations 4 [1..9] 
+3
source share
4 answers

Here is my solution:

 import Control.Arrow select :: [a] -> [(a, [a])] select [] = [] select (x:xs) = (x, xs) : map (second (x:)) (select xs) perms :: Int -> [a] -> [[a]] perms 0 _ = [[]] perms n xs = do (y, ys) <- select xs fmap (y:) (perms (n - 1) ys) 

He is very lazy and even works for endless lists, although the output there is not very useful. I did not bother to realize diagonalization or something like that. For leaf lists, this is great.

+5
source
 pick :: Int -> [a] -> [[a]] pick 0 _ = [[]] pick _ [] = [] pick n (x : xs) = map (x :) (pick (n - 1) xs) ++ pick n xs perms :: Int -> [a] -> [[a]] perms nl = pick nl >>= permutations 
+2
source
 replicateM 4 [1..9] 

I will do it for you. This is in Control.Monad .

+1
source

How about this

 import Data.List (delete) perms :: (Eq a) => Int -> [a] -> [[a]] perms 0 _ = [[]] perms _ [] = [[]] perms n xs = [ (x:ys) | x <- xs, ys <- perms (n-1) (delete x xs) ] 

Basically, he says that a permutation of n elements from a set is a choice of any element as the first element of the result, then the rest is a permutation of n-1 elements from the rest of the set. Plus some basic cases. It is assumed that the items in the list are unique.

0
source

All Articles