Power set: Difference between revisions

m (→‎{{header|zkl}}: formatting)
Line 1,179:
["b", "c"]
["a", "b", "c"]</pre>
 
 
=== Alternative: ===
 
An almost verbatim translation of the Haskell code in D.
 
Since D doesn't foldr, I've also copied Haskell's foldr implementation here.
 
Main difference from the Haskell:
#It isn't lazy (but it could be made so by implementing this as a generator)
 
Main differences from the version above:
#It isn't lazy
#It doesn't rely on integer bit fiddling, so it should work on arrays larger than size_t.
 
<lang d>
// Haskell definition:
// foldr f z [] = z
// foldr f z (x:xs) = x `f` foldr f z xs
S foldr(T, S)(S function(T, S) f, S z, T[] rest) {
return (rest.length == 0) ? z : f(rest[0], foldr(f, z, rest[1..$]));
}
 
// Haskell definition:
//powerSet = foldr (\x acc -> acc ++ map (x:) acc) [[]]
T[][] powerset(T)(T[] set) {
import std.algorithm;
import std.array;
// Note: The types before x and acc aren't needed, so this could be made even more concise, but I think it helps
// to make the algorithm slightly clearer.
return foldr( (T x, T[][] acc) => acc ~ acc.map!(accx => x ~ accx).array , [[]], set );
}
</lang>
 
=={{header|Déjà Vu}}==
Anonymous user