Reputation: 133
This is a problem I've been working through on List comprehension. I know that it should be solved with recursion, but I am not sure exactly how the Haskell syntax works for the recursive case.
Here's the problem:
Given a list of strings, output all possible combinations of those strings and 3 variables [C,U,I]. For example,
list ["vC", "vU", "vI"] == [[("vC",C),("vU",C),("vI",C)],[("vC",I),("vU",C),("vI",C)],[("vC",U),("vU",C),("vI",C)] ,[("vC",C),("vU",I),("vI",C)],[("vC",I),("vU",I),("vI",C)],[("vC",U),("vU",I),("vI",C)] ,[("vC",C),("vU",U),("vI",C)],[("vC",I),("vU",U),("vI",C)],[("vC",U),("vU",U),("vI",C)] ,[("vC",C),("vU",C),("vI",I)],[("vC",I),("vU",C),("vI",I)],[("vC",U),("vU",C),("vI",I)] ,[("vC",C),("vU",I),("vI",I)],[("vC",I),("vU",I),("vI",I)],[("vC",U),("vU",I),("vI",I)] ,[("vC",C),("vU",U),("vI",I)],[("vC",I),("vU",U),("vI",I)],[("vC",U),("vU",U),("vI",I)] ,[("vC",C),("vU",C),("vI",U)],[("vC",I),("vU",C),("vI",U)],[("vC",U),("vU",C),("vI",U)] ,[("vC",C),("vU",I),("vI",U)],[("vC",I),("vU",I),("vI",U)],[("vC",U),("vU",I),("vI",U)] ,[("vC",C),("vU",U),("vI",U)],[("vC",I),("vU",U),("vI",U)],[("vC",U),("vU",U),("vI",U)]]
Edit: So this is what I have tried so far.
list :: [String] -> [Dict]
list [] = [[]]
list xs = [[(x,y)] | y<-[C,U,I], x <- xs]
However, when I run a test case with three variables, it only outputs:
[[("vC",C)],[("vU",C)],[("vI",C)],[("vC",U)],[("vU",U)],[("vI",U)],[("vC",I)],[("vU",I)],[("vI",I)]]
Upvotes: 0
Views: 480
Reputation: 52270
ok, let's try to get you there step by step
Maybe you've seen the comment already but here it is with the most important step but in:
list [] = [[]]
list (x:xs) = [(x,c) : ys | c <- ???, ys <- list xs ]
notice the two cases corresponding to the two list-constructors - that's typical and you missed the second one.
Now you only have to:
???
it should be easyI guess you got it - just in case the answer is:
list [] = [[]]
list (x:xs) = [(x,c) : ys | ys <- list xs, c <- [C,I,U] ]
Upvotes: 1