Get all possible combinations of k elements from the list

I need a function that does the same thing as itertools.combinations(iterable, r)in python

So far I have come up with this:

{-| forward application -}
x -: f = f x
infixl 0 -:

{-| combinations 2 "ABCD" = ["AB","AC","AD","BC","BD","CD"] -}
combinations :: Ord a => Int -> [a] -> [[a]]
combinations k l = (sequence . replicate k) l -: map sort -: sort -: nub
    -: filter (\l -> (length . nub) l == length l)

Is there a more elegant and efficient solution?

+4
source share
4 answers

(Based on @JoseJuan answer)

You can also use list comprehension to filter out those where the second character is strictly not less than the first:

[x| x <- mapM (const "ABCD") [1..2], head x < head (tail x) ]
+4
source

xstake the elements nto nmake

mapM (const xs) [1..n]

all combinations (n ​​= 1, 2, ...)

allCombs xs = [1..] >>= \n -> mapM (const xs) [1..n]

if you need without repetition

filter ((n==).length.nub)

then

combinationsWRep xs n = filter ((n==).length.nub) $ mapM (const xs) [1..n]
+7
source

( @FrankSchmitts)

map (const x) [1..n] == replicate n x,

[x| x <- sequence (replicate 2 "ABCD"), head x < head (tail x) ]

2 k, , , 2

[ [x1,x2] | x1 <- "ABCD", x2 <- "ABCD", x1 < x2 ]

.

k , . Id :

f 0 _  = [[]]
f _ [] = []
f k as = [ x : xs | (x:as') <- tails as, xs <- f (k-1) as' ]

( , as, , nub as )

+3

SO:

n

, .

+3

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


All Articles