I Have a powerset function which creates a list [[a]] but the largest [a] is worked out first, meaning the whole algorithm has to run before I can get the smaller values.
I need a function which returns a powerset, in ascending order, so I could take the first n values of the function and the whole algorithm would not need to run.
Current simple algorithm
powerset :: [a] -> [[a]]
powerset [] = [[]]
powerset (x:xs) = [x:ps | ps <- powerset xs] ++ powerset xs
I don't understand what you mean by ascending order, but consider this solution:
We start with the powerset of the empty list, which is
[[]], and expand it for each new element we encounter in the input list. The expansion is by appending the new element in each sublist we already emitted.It requires that we append elements to the sublists exponentially many times, so I also considered using
Data.DListfrom thedlistpackage that provides an efficientsnocoperator that appends new elements to the end of the list:In my (rough) experiments, though, the first solution uses way less memory in the REPL and thus finishes faster for bigger input lists.
In both cases, this is what you get at the end: