Created
March 6, 2017 15:08
-
-
Save xiaohanyu/384c93892f781af1dc6524380725c780 to your computer and use it in GitHub Desktop.
Revisions
-
xiaohanyu created this gist
Mar 6, 2017 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,31 @@ Here're two powerset function implemented in Python and Haskell. #+BEGIN_SRC python :tangle powerset.py 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 #+END_SRC #+BEGIN_SRC haskell :tangle powerset.hs powerset :: [a] -> [[a]] powerset [] = [[]] powerset [x] = [[], [x]] powerset (x:xs) = [x:px | px <- powerset(xs)] ++ powerset(xs) #+END_SRC And we can see that in a language with [[https://en.wikipedia.org/wiki/Pattern_matching][Pattern matching]], [[https://en.wikipedia.org/wiki/Lazy_evaluation][Lazy evaluation]] and immutable data structures like Haskell, it's really easy and elegant to implement some mathematical functions.