I’ve been using the following code to get all combinations of a pre-determined amount of numbers:
getList x = [ [a,b,c] | a <- [1..x], b <- [1..x], c <- [1..x]]
This was fine to begin with, but I’m looking to expand the program to handle very large lists, and I keep thinking there must be a better way to do this. How would I create a function that takes the same parameter x as here, and also another parameter for how many items the sublists have. For four items I would go and modify the code:
getList x = [ [a,b,c,d] | a <- [1..x], b <- [1..x], c <- [1..x], d <- [1..x]]
It doesn’t need to be a list comprehension. Thank you for any help.
I believe what you want would be the
replicateMfunction inControl.Monad.The list monad is based on “trying all possible combinations”, and plain
replicatecreates a list by repeating an item some number of times. So the result ofreplicateMis, given some list of possible values, a list of all possible ways to select an item from that list some number of times.For example:
So to extend your function to arbitrary repetitions, you’d use something like:
…where your original
getListwould be equivalent togetListN 3.