Haskell Prelude 是否有 union 和 intersect 实现?

发布于 2024-11-06 18:28:55 字数 503 浏览 1 评论 0原文

标准 Prelude 函数中是否有实现集合的并集和交集?

union      :: (Eq a) => [a] -> [a] -> [a]
intersect  :: (Eq a) => [a] -> [a] -> [a]

如果不是,有人可以说我的实现是否有效,(充分利用懒惰和前奏功能)

unionSet :: (Eq a) => [a] -> [a] -> [a]
unionSet as bs = foldl (\xs y -> if elem y xs then xs else xs ++ [y]) as bs

intersectSet :: (Eq a) => [a] -> [a] -> [a]
intersectSet as bs = let ns = [ a | a <- as, elem a bs] in [ b | b <- bs, elem b ns]

Is there in the Standard Prelude functions which implement the union and the intersection of sets ?

union      :: (Eq a) => [a] -> [a] -> [a]
intersect  :: (Eq a) => [a] -> [a] -> [a]

If no, may somebody can said if my implementation is efficient, (make good use of laziness and prelude function)

unionSet :: (Eq a) => [a] -> [a] -> [a]
unionSet as bs = foldl (\xs y -> if elem y xs then xs else xs ++ [y]) as bs

intersectSet :: (Eq a) => [a] -> [a] -> [a]
intersectSet as bs = let ns = [ a | a <- as, elem a bs] in [ b | b <- bs, elem b ns]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轮廓§ 2024-11-13 18:28:55

union< /code>intersect 标准库中列表的函数,位于 Data.List 中,但不在 Prelude 中本身。

就效率而言,我将对上述所有内容说“不”,无论是您的还是标准库的。实际上,仅使用 Eq 约束就无法对列表进行有效的操作。也就是说,您可能仍然会在 Data.List 中找到信息丰富的实现 - 请参阅上面的链接,我已直接指向相关源。

编辑 - 作为为了后代的简短附录,请务必查看 Don 的答案,了解您实际上想要用于此目的的内容,而不是狭隘的问题“这些功能是否存在”。

There are union and intersect functions on lists in the standard libraries, located in Data.List but not in the Prelude itself.

As far as efficiency goes, I'm going to say "no" to all of the above, both yours and the standard library's. There's really no way either can ever be efficient operations on a list with only an Eq constraint. That said, you may still find the implementation in Data.List informative--see the links above, which I've pointed directly to the relevant source.

Edit -- As a brief addendum for the sake of posterity, be sure to see Don's answer for what you actually want to use for this purpose, rather than the narrower question of "do these functions exist at all".

挖鼻大婶 2024-11-13 18:28:55

正如 camccann 指出的那样,基础库提供了列表版本。如果您想要更高效的东西,请考虑数据.Set,它提供:

union :: Ord a => Set a -> Set a -> Set a

intersection :: Ord a => Set a -> Set a -> Set a

复杂度O(n+m)

The base library provides list versions, as camccann points out. If you want something a bit more efficient, consider Data.Set, which provides:

union :: Ord a => Set a -> Set a -> Set a

intersection :: Ord a => Set a -> Set a -> Set a

with complexity O(n+m).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文