Skip to content

Instantly share code, notes, and snippets.

@xiaohanyu
Created March 6, 2017 15:08
Show Gist options
  • Save xiaohanyu/384c93892f781af1dc6524380725c780 to your computer and use it in GitHub Desktop.
Save xiaohanyu/384c93892f781af1dc6524380725c780 to your computer and use it in GitHub Desktop.
A demo powerset function implemented in Haskell and Python.

Here’re two powerset function implemented in Python and Haskell.

import copy

def powerset(s):
    if s == []:
        return [[]]
    elif len(s) == 1:
        return [[], s]
    else:
        powerset1 = powerset(s[1:])
        powerset2 = []
        for ss in powerset1:
            new_ss = copy.deepcopy(ss)
            new_ss.insert(0, s[0])
            powerset2.append(new_ss)

        return powerset1 + powerset2
powerset :: [a] -> [[a]]
powerset [] = [[]]
powerset [x] = [[], [x]]
powerset (x:xs) = [x:px | px <- powerset(xs)] ++ powerset(xs)

And we can see that in a language with Pattern matching, Lazy evaluation and immutable data structures like Haskell, it’s really easy and elegant to implement some mathematical functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment