Home > Software engineering >  All combinations of a list into an infinite list in haskell
All combinations of a list into an infinite list in haskell

Time:12-05

My task is to implement a function allCombinations, in Haskell, which returns every possible combination of a given list as an infinite list.

Since i couldn't find a solution, which does not include imports, i will ask it again. I'm new to Haskell and my task is to create a function allCombinations :: [a] -> [[a]], which creates an infinite list of possible combinations. For Example: take 10 (allCombinations [True,False]), in return I should get [[],[True],[False],[True,True],[False,True],[True,False],[False,False],[True,True,True],[False,True,True],[True,False,True]]. I have found a few solutions, but all of them included imports and i need to solve this without any imports.

CodePudding user response:

You can work with recursion here. This starts with the empty list, and then you recurse where you prepend with the given list, and the items in the list, so:

allCombinations :: [a] -> [[a]]
allCombinations xs = zs
  where zs = [] : [ (y:ys) | ys <- zs, y <- xs ]
  • Related