3 ms·
How about demonstrating the power of laziness by generating the power set of a set? (Taken from Learn You a Haskell). powerset :: [a] -> [[a]] powerset x
by cgh 13y ago
How about demonstrating the power of laziness by generating the power set of a set? (Taken from Learn You a Haskell).
powerset :: [a] -> [[a]]
powerset xs = filterM (\x -> [True, False]) xs
ghci> powerset [1,2,3]
[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]
Edit: I read LYaH some time ago but this example stuck with me because it's both wonderful and mind-blowing.
- platz 13y agoHere's a recursive definition which is less cool but less 'magic' powerset :: [a] -> [[a]] powerset [] = [[]] powerset (x:xs) = yss ++ map (x:) yss where yss = powerset xs > powerset [1,2,3] [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]