1

I have this function:

subsetsOfThree [] = []
subsetsOfThree [x,y,z] = [[x,y,z]]
subsetsOfThree fls@(x:y:z:xs) = ([x,y,z] : subsetsOfThree (xs))  ++ 
  (subsetsOfThree (x:xs)) ++
  (subsetsOfThree (y:xs)) ++ 
  (subsetsOfThree (z:xs)) ++ 
  (subsetsOfThree (x:y:xs)) ++
  (subsetsOfThree (x:z:xs)) ++ 
  (subsetsOfThree (y:z:xs)) 
subsetsOfThree _ = []

And it take only the subsets of length 3, but I cannot get rid of converting it in equivalent list comprehension, I tryed:

subsetsOfThree [] = []
subsetsOfThree [x,y,z] = [[x,y,z]]
subsetsOfThree (x:y:z:xs) = [xs6 | xs1 <- subsetsOfThree xs,
 xs2 <- [xs1, (x:xs)],
 xs3 <- [xs2, (y:xs)],
 xs4 <- [xs3, (z:xs)],
 xs5 <- [xs4, (x:y:xs)],
 xs6 <- [xs5, (y:z:xs)]
 ]
subsetsOfThree _ = [] 

But it always returns []

Any clue will be appreciated

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • Consider that `subsetsOfThree [1,2,3,4]` makes one recursive call `subsetsOfThree [4]`, which results in `[]`. Since `xs1` is drawing from an empty list, none of the other generators are used. – chepner Oct 09 '19 at 21:00

1 Answers1

4

I think you might want to exploit the tails helper function:

subsetsOfThree ws = [ [x,y,z] | (x:xs) <- tails ws, (y:ys) <- tails xs, z <- ys ]

This relies on (_:_) <- list generating nothing when list is empty, rather than throwing a runtime error.

chi
  • 111,837
  • 3
  • 133
  • 218
  • You even make my function make sense and work properly, I will quote you in an answer of mine, and give to you a bounty if stack overflow let me – developer_hatch Oct 09 '19 at 20:59
  • I add the bounty in this question https://stackoverflow.com/questions/58262463/filter-subsets-based-on-length because I cannot add it in this one, if you answer there you get the bounty for you help, thanks so much – developer_hatch Oct 09 '19 at 21:04
  • @DamiánRafaelLattenero Thank you, but don't worry about giving me a bounty. Quoting with credit, as you did, is already enough. – chi Oct 09 '19 at 21:37
  • @chi the bounty is already there. the rep is already spent. :) – Will Ness Oct 10 '19 at 16:28