I am very bad at wording things, so please bear with me.
I am doing a problem that requires me to generate all possible numbers in the form of a lists of lists, in Haskell.
For example if I have x = 3 and y = 2, I have to generate a list of lists like this:
[[1,1,1], [1,2,1], [2,1,1], [2,2,1], [1,1,2], [1,2,2], [2,1,2], [2,2,2]]
x and y are passed into the function and it has to work with any nonzero positive integers x and y.
I am completely lost and have no idea how to even begin.
For anyone kind enough to help me, please try to keep any math-heavy explanations as easy to understand as possible. I am really not good at math.
Assuming that this is homework, I’ll give you the part of the answer, and show you how I think through this sort of problem. It’s helpful to experiment in GHCi, and build up the pieces we need. One thing we need is to be able to generate a list of numbers from 1 through
y. Supposeyis 7. Then:But as you’ll see in a moment, what we really need is not a simple list, but a list of lists that we can build on. Like this:
This basically says to take each element in the array, and prepend it to the empty list
[]. So now we can write a function to do this for us.Next, we need a way to prepend a new element to every element in a list of lists. Something like this:
(I used 99 here instead of, say, 1, so that you can easily see where the numbers come from.) So we could write a function to do that:
Ultimately, we want to be able to take a list and a list of lists, and invoke
prependon every element in the list to every element in the list of lists. We can do that using themapfunction again. But as it turns out, it will be a little easier to do that if we switch the order of the arguments toprepend, like this:Then we can do something like this:
So now we can write that function:
Using your example, if x=2 and y=3, then the answer we need is:
(If that was all we needed, we could have done this more easily using a list comprehension. But since we need to be able to do this for an arbitrary x, a list comprehension won’t work.)
Hopefully you can take it from here, and extend it to arbitrary x.