函数式编程功能

发布于 2024-11-04 14:42:43 字数 27 浏览 0 评论 0原文

如何编写两个列表或集合的并集的函数程序?

How to write a functional program for the union of two lists or sets?

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

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

发布评论

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

评论(2

剪不断理还乱 2024-11-11 14:42:43

这取决于语言,但通常会有一个递归解决方案,涉及遍历标识共享元素的集合。

例如,在 Haskell 中的原生 Data.Set 类型,

union :: Ord a => Set a -> Set a -> Set a
union Tip t2  = t2
union t1 Tip  = t1
union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2

hedgeUnion _     _     t1 Tip
  = t1
hedgeUnion cmplo cmphi Tip (Bin _ x l r)
  = join x (filterGt cmplo l) (filterLt cmphi r)
hedgeUnion cmplo cmphi (Bin _ x l r) t2
  = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
           (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
  where
    cmpx y  = compare x y

或者更简单地说,对于列表:

unionBy                 :: (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy eq xs ys        =  xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs

It depends on the language, but generally, there'll be a recursive solution involving traversal of the sets identifying shared elements.

E.g. in Haskell on the native Data.Set type,

union :: Ord a => Set a -> Set a -> Set a
union Tip t2  = t2
union t1 Tip  = t1
union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2

hedgeUnion _     _     t1 Tip
  = t1
hedgeUnion cmplo cmphi Tip (Bin _ x l r)
  = join x (filterGt cmplo l) (filterLt cmphi r)
hedgeUnion cmplo cmphi (Bin _ x l r) t2
  = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
           (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
  where
    cmpx y  = compare x y

Or more simply, for lists:

unionBy                 :: (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy eq xs ys        =  xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs
醉生梦死 2024-11-11 14:42:43

这听起来像是一个家庭作业问题,但我会咬牙切齿。在Python中:

lambda x, y: x + filter(lambda z: z not in x, y)

This sounds like a homework question, but I'll bite. In Python:

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