Reputation: 2871
I have tried to solve this problem before, and I've searched for a solution and could never find one.
I need a function that takes a list xs and an integer n and returns all list of length n with elements from xs. For example:
function [0,1] 3 = [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
I have tried this:
list _ 0 = []
list xs n = do
y <- xs
ps <- list xs (n-1)
return y : ps
and this:
list _ 0 = []
list xs n = do
y <- xs
y : list xs (n-1)
None work as intended. I want to know two things: Why doesn't these work? How should I modify them so that they work?
Upvotes: 1
Views: 668
Reputation: 89113
You're very close! Your problem is your base case, list _ 0 = []
.
What you're saying there is that there are no lists of length 0 with elements from xs, when in fact there is one, the empty list.
Try
list _ 0 = [[]]
list xs n = do
y <- xs
ps <- list xs (n-1)
return $ y : ps
Upvotes: 8