haskell - 为什么Data.Set没有powerset函数?

标签 haskell powerset

我查看了Data.Set,发现它没有powerset函数。为什么?

我可以这样实现:

import Data.Set (Set, empty, fromList, toList, insert)

powerset :: (Ord a) => Set a -> Set (Set a)
powerset s = fromList $ map (fromList) (powerList $ toList s)

powerList :: [a] -> [[a]]
powerList [] = [[]]
powerList (x:xs) = powerList xs ++ map (x:) (powerList xs)

但这似乎不是最有效的方法。好的,我也可以写

powerList :: [a] -> [[a]]
powerList = filterM (const [True, False])

但我还是想知道为什么Data.Set没有powerset函数。

此外,powerset::(Ord a) => Set a -> Set (Set a) 的最佳编写方式是什么?

最佳答案

有趣的是,前几天我实际上在 Haskell 中实现了 powerset 只是为了好玩 a comment at /r/python .

import Data.Set
import Prelude hiding (map)

powerset s
    | s == empty = singleton empty
    | otherwise = map (insert x) pxs `union` pxs
        where (x, xs) = deleteFindMin s
              pxs = powerset xs

这很像 camccann 在上面的评论中所描述的那样。 Set 的快速 union 应该会比列表版本提高速度。

关于haskell - 为什么Data.Set没有powerset函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6428279/

相关文章:

algorithm - 幂集中的动态规划

recursion - 如何在 LISP 中为列表的每个元素添加一个对象?

haskell - 如何在 Haskell 项目中使用 DLL?

haskell - 如何使用 Diagrams 创建这个简单的 gif 动画

haskell - 判断一个值是否是 Haskell 中的函数

list - prolog 中列表的所有元素的所有子集

scheme - 如何在 DrRacket 中做力量组?

haskell - cabal : error while loading shared libraries: libHSzlib-0. 5.4.1-ghc7.6.3.so

haskell - Data.FixedList源代码中的 `Cons`是什么?

java - 获取列表的 Powerset 的最佳方法(递归)