Haskell, combination with repetitions + permutations

Suppose I have a list with items, for example [1,2,3,4,5,6,7,8]. I want to create all permutations of these elements with length N.

So for N = 4this to be [[1,1,1,1],[1,1,1,2],[1,1,2,1],[1,2,1,1],[2,1,1,1],..]etc.

comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs

Now, to get these lists first, I find all combinations with repetitions for my list, so [[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,1,4],[1,1,1,5],...]for each list I find all permutations, and if the permutation is not in the list, I add it to the list.

permutations1 :: Eq a => [a] -> [[a]]
permutations1 []   = [[]]
permutations1 list = [(x:xs) | x <- list, xs <- permutations1 $ delete1 x list]

delete1:: Eq a => a -> [a] -> [a]
delete1 _ [] = [] 
delete1 a (b:bc) | a == b = bc 
                 | otherwise = b : delete1 a bc

And this is how I get the desired response.

I understand that this is really (really) bad, but I don’t understand haskell enough to write a function that combines these functions.

+4
source share
1 answer

. haskell replicateM (.. )

\> import Control.Monad (replicateM)
\> length $ replicateM 4 [1..5]   -- should output 5^4
625
\> replicateM 4 [1..5]
[[1,1,1,1],[1,1,1,2],[1,1,1,3],[1,1,1,4],[1,1,1,5],[1,1,2,1],[1,1,2,2],[1,1,2,3],[1,1,2,4],[1,1,2,5]] ....

4 5 , 4 5 ; [1..5] 4 , replicateM 4.

Monad (.. M) , .

monad type . , , [1..5], ; , 4 , 5 , 5^4 .

+9

Source: https://habr.com/ru/post/1626664/


All Articles