为什么Data.Set没有powerset功能?

Mar*_*coS 8 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)
Run Code Online (Sandbox Code Playgroud)

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

powerList :: [a] -> [[a]]
powerList = filterM (const [True, False])
Run Code Online (Sandbox Code Playgroud)

但是,我仍然想知道为什么Data.Set没有powerset功能.

另外,最好的写作方式是powerset :: (Ord a) => Set a -> Set (Set a)什么?

Dan*_*ton 12

有趣的是,我实际上是powerset在Haskell中实现的,只是为了在/ 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
Run Code Online (Sandbox Code Playgroud)

这与他上面的评论中描述的camccann非常相似.Set快速union应该比列表版本提速.

  • 请注意,这可能仍然比访问"Set"内部的算法效率低.我相信,表示是一个平衡的二叉树,并且这里的并集总是两组相等的大小,所有元素都比另一组的所有元素都大或小,因此仅仅将大小相加并创建一个新的就足够了root用两个集合作为分支. (2认同)