是否有联合和相交 Haskell Prelude 实现?

编程入门 行业动态 更新时间:2024-10-12 08:27:10
本文介绍了是否有联合和相交 Haskell Prelude 实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Standard Prelude 函数中是否有实现并集和集合交集的功能?

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]

推荐答案

有union 和 intersect 函数在标准库中的列表上,位于 Data.List但不在 Prelude 本身中.

就效率而言,我将对以上所有内容说不",无论是您的还是标准库的.在只有 Eq 约束的列表上,真的没有办法进行有效的操作.也就是说,您仍然可以在 Data.List 中找到信息丰富的实现——请参阅上面的链接,我已直接指向相关来源.

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.

编辑 -- 作为一个简短的附录,以供后人参考,请务必查看 Don 对您实际想要用于此目的的回答,而不是这些功能是否存在"的狭义问题.

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".

更多推荐

是否有联合和相交 Haskell Prelude 实现?

本文发布于:2023-10-24 20:41:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524950.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Haskell   Prelude

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!