I came up with what I think is an elegant use of monadic code, while working on a program to compute solutions to the Postage Stamp Problem. The problem asks:
Consider that an envelope is able to hold a limited number of postage stamps. Then, consider the set of the values of the stamps – positive integers only. Then, what is the smallest total postage which cannot be put onto the envelope?
The algorithm below takes a number of stamps that can fit and a total postage to apply and returns a list of all the sets of different stamp values that can be combined to form the target postage sum:
1 2 3 4 5 6
Thus the potential stamp combinations for a letter which can hold three stamps and costing 5 cents to mail would be:
As you can see, the algorithm also produces ordered lists naturally!
But perhaps all we care about are unique stamp values that. If we want to
adjust our goal such that the algorithm returns a list of all sets of unique
stamp values sufficient to create the target postage, we need only adjust the
Similarly we could drop the zeros (which mean “no stamp” in our case) from the beginnings of each set if we desired. The above code have applications to many similar problems including Subset Sum, and Knapsack as well as other partitioning problems.