Get list of lists without recursion

I'm trying to get all lists with length 4 from alphabet [0..9] with unique elements.

allNumbers = [a | let list = [0..9], x1 <- list, x2 <- list, x3 <- list, x4 <- list, let a = [x1,x2,x3,x4], nub a == a]

How can I get some simplest and nicest version of that? What if I need all such lists with length 10 (I don't want to copypasting x# <- list 10 times)? Non-recursive answer is encouraged.

Upvotes: 3

Views: 364

Answers (1)

Matt Fenwick
Matt Fenwick

Reputation: 49085

use sequence:

Prelude> let a = [0..9]
Prelude> sequence $ replicate 4 a

This relies on the monad instance for list. Then you can add in the nub part with filter:

filter (\x -> nub x == x) $ sequence $ replicate 4 [0 .. 9]

Update: as pointed out in a comment, you could also use replicateM (which I was not aware of):

Prelude> :m + Control.Monad
Prelude> filter (\x -> nub x == x) $ replicateM 4 [0 .. 9]

Upvotes: 3

Related Questions