A declarative way to calculate power sets in JavaScript (with a short detour to Haskell)

Zoltán Tamási
5 min readApr 19, 2019

There is a definite differentiation between declarative and imperative ways of programming. The latter used to be explained as the method when you answer the question: “What are the steps/changes to do sequentially?”, while the former method answers “What is needed?” or even: “How can the solution be derived from the problem, or a solution for a smaller sub-problem?”

One form of being declarative is recursion. Recursion happens when — in an imperative wording — a function calls itself in its body, or — in a declarative wording — when a function refers to itself.

The power set problem as an example

A power set of a set is a set that contains each and every subset of it, including the empty set and the actual set itself.

The power set of the empty set is the empty set.
For example the power set of {x} is: {{}, {x}}

And the power set of {x, y} is {{}, {x}, {y}, {x, y}}

Imperative approach

An imperative way to write an algorithm could be to start with a set containing the empty set as the initial candidate result set of subsets, and then iterating through each of the elements of the input set and “populate” this candidate…

--

--