No native set type in Go. While the associative array trick mentioned in the task description works well in Go in most situations, it does not work here because we need sets of sets, and converting a general set to a hashable value for a map key is non-trivial.

Instead, this solution uses a simple (non-associative) slice as a set representation. To ensure uniqueness, the element interface requires an equality method, which is used by the
set add method. Adding elements with the add method ensures the uniqueness property.

While the "add" and "has" methods make a usable set type, the power set method implemented here computes a result directly without using the add method. The algorithm ensures that the result will be a valid set as long as the input is a valid set. This allows the more efficient append function to be used.

package main

import("bytes""fmt""strconv")

// types needed to implement general purpose sets are element and set

// element is an interface, allowing different kinds of elements to be// implemented and stored in sets.type elem interface{// an element must be distinguishable from other elements to satisfy// the mathematical definition of a set. a.eq(b) must give the same// result as b.eq(a). Eq(elem)bool// String result is used only for printable output. Given a, b where// a.eq(b), it is not required that a.String() == b.String().fmt.Stringer}

// integer type satisfying element interfacetype Int int

func(i Int) Eq(e elem)bool{ j, ok := e.(Int)return ok && i== j}

func(i Int) String()string{return strconv.Itoa(int(i))}

// a set is a slice of elem's. methods are added to implement// the element interface, to allow nesting.type set []elem

Builds on the Combinations solution. Sets are not a "natural" collection type in Groovy. Lists are much more richly supported. Thus, this solution is liberally sprinkled with coercion from Set to List and from List to Set.

Note: In this example, LinkedHashSet was used throughout for Set coercion. This is because LinkedHashSet preserves the order of input, like a List. However, if order does not matter you could replace all references to LinkedHashSet with Set.

listPowerset describes the result as all possible (using the list monad) filterings (using filterM) of the input list, regardless (using const) of each item's value. powerset simply converts the input and output from lists to sets.

A method using only set operations and set mapping is also possible. Ideally, Set would be defined as a Monad, but that's impossible given the constraint that the type of inputs to Set.map (and a few other functions) be ordered.

The two examples below show the similarities and differences between constructing an explicit representation of the solution, i.e. a set containing the powerset, and one using generators. The basic recursive algorithm is the same in each case, but wherever the first stores part of the result away, the second uses 'suspend' to immediately pass the result back to the caller. The caller may then decide to store the results in a set, a list, or dispose of each one as it appears.

procedure power_set (s) result :=set()if*s =0theninsert(result,set())# empty setelse{ head :=set(?s)# take a random element# and find powerset of remaining part of set tail_pset := power_set (x -- head) result ++:= tail_pset # add powerset of remainder to resultsevery ps :=!tail_pset do# and add head to each powerset from the remainderinsert(result, ps ++ head)}return resultend

In the typical use, this operation makes sense on collections of unique elements.

~.12321123 #ps 1232132 #ps ~.123218

In other words, the power set of a 5 element set has 32 sets where the power set of a 3 element set has 8 sets. Thus if elements of the original "set" were not unique then sets of the power "set" will also not be unique sets.

This implementation works on idea that each element in the original set can either be in the power set or not in it. With n elements in the original set, each combination can be represented by a binary string of length n. To get all possible combinations, all you need is a counter from 0 to 2n - 1. If the kth bit in the binary string is 1, the kth element of the original set is in this combination.

Sets are not an explicit data type in MATLAB, but cell arrays can be used for the same purpose. In fact, cell arrays have the benefit of containing any kind of data structure. So, this powerset function will work on a set of any type of data structure, without the need to overload any operators.

The standard library already implements a proper Set datatype. As the base type is unspecified, the powerset must be parameterized as a module. Also, the library is lacking a map operation, which we have to implement first.

This module has an iterator over the power set. Note that it does not enforce that the input array is a set (no duplication). If each subset is processed immediately, this has an advantage of very low memory use.

Similar to the Pari/GP solution, uses vecextract with an integer mask to select elements. Note that it does not enforce that the input array is a set (no duplication). This also has low memory if each subset is processed immediately and the range is applied with a loop rather than a map. A solution using vecreduce could be done identical to the array reduce solution shown later.

(Note: For a ready-to-use module that uses this approach, and comes with all the standard set methods that you would expect, see the CPAN module Set::Tiny)

The limitation of this approach is that only primitive strings/numbers are allowed as hash keys in Perl, so a Set of Set's cannot be represented, and the return value of our powerset function will thus have to be a list of sets rather than being a Set object itself.

We could implement the function as an imperative foreach loop similar to the Set::Object based solution above, but using list folding (with the help of Perl's List::Util core module) seems a little more elegant in this case:

If you don't actually need a proper set data-type that guarantees uniqueness of its elements, the simplest approach is to use arrays to store "sets" of items, in which case the implementation of the powerset function becomes quite short.

If the initial set is quite large, constructing it's powerset all at once can consume lots of memory.

If you want to iterate through all of the elements of the powerset of a set, and don't mind each element being generated immediately before you process it, and being thrown away immediately after you're done with it, you can use vastly less memory. This is similar to the earlier solutions using the Algorithm::Combinatorics and ntheory modules.

The following algorithm uses one bit of memory for every element of the original set (technically it uses several bytes per element with current versions of Perl). This is essentially doing a vecextract operation by hand.

}$OFS=" "$setA= power-set@(1,2,3,4)"number of sets in setA: $($setA.Count)""sets in setA:"$OFS=", "$setA|foreach{"{"+"$_"+"}"}$setB=@()"number of sets in setB: $($setB.Count)""sets in setB:"$setB|foreach{"{"+"$_"+"}"}$setC=@(@(),@(@()))"number of sets in setC: $($setC.Count)""sets in setC:"$setC|foreach{"{"+"$_"+"}"}$OFS=" "

def list_powerset(lst):# the power set of the empty set has one element, the empty set result =[[]]for x in lst:# for every additional element in our set# the power set consists of the subsets that don't# contain this element (just take the previous power set)# plus the subsets that do contain the element (use list# comprehension to add [x] onto everything in the# previous power set) result.extend([subset + [x]for subset in result])return result

list_powerset computes the power set of a list of distinct elements. powerset simply converts the input and output from lists to sets. We use the frozenset type here for immutable sets, because unlike mutable sets, it can be put into other sets.

If you take out the requirement to produce sets and produce list versions of each powerset element, then add a print to trace the execution, you get this simplified version of the program above where it is easier to trace the inner workings

If you list the members of the set and include them according to if the corresponding bit position of a binary count is true then you generate the powerset.
(Note that only frozensets can be members of a set in the second function)

def powersequence(val):''' Generate a 'powerset' for sequence types that are indexable by integers. Uses a binary count to enumerate the members and returns a list

The list "temp" is a compromise between the speed costs of doing
arithmetic and of creating new lists (since R lists are immutable,
appending to a list means actually creating a new list object).
Thus, "temp" collects new subsets that are later added to the power set.
This improves the speed by 4x compared to extending the list "ps" at every step.

# Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/ # See the link if you want a shorter version. # This was intended to show the reader how the method works. classArray# Adds a power_set method to every array, i.e.: [1, 2].power_setdef power_set

# Injects into a blank array of arrays.# acc is what we're injecting into# you is each element of the array inject([[]])do|acc, you| ret = []# Set up a new array to add into acc.eachdo|i|# For each array in the injected array, ret << i # Add itself into the new array ret << i +[you]# Merge the array with a new array of the current elementend ret # Return the array we're looking at to inject more.end

end

# A more functional and even clearer variant.def func_power_set inject([[]]){|ps,item|# for each item in the Array ps +# take the powerset up to now and add ps.map{|e| e +[item]}# it again, with the item appended to each element}endend

This generates the lists of combinations of all possible lengths, from 0 to the length of s and catenates them. The comb function generates a lazy list, so it is appropriate to use mappend* (the lazy version of mappend) to keep the behavior lazy.

A complete program which takes command line arguments and prints the power set in comma-separated brace notation:

Sets are a built in type constructor in Ursala, represented as
lexically sorted lists with duplicates removed.
The powerset function is a standard library function,
but could be defined as shown below.