我似乎无法理解“列表差异”; (\\) 操作员

发布于 2024-11-10 18:39:41 字数 75 浏览 0 评论 0原文

我在 Haskell 中听说过术语“列表差异”(\\) 运算符,但仍然不太知道如何理解它。有什么例子或想法吗?

I have heard the term 'list difference' (\\) operator in Haskell but still don't quite know how to get my head around it. Any examples or ideas?

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

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

发布评论

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

评论(4

轻拂→两袖风尘 2024-11-17 18:39:41

( \\) 运算符(和 差异 function) 实现 设置差异,所以,如果您有两个列表, ab,它仅返回 a 中不在 b 中的元素,如图所示:

在此处输入图像描述

The (\\) operator (and the difference function) implements set difference, so, if you have two lists, a and b, it returns only those elements of a that are not in b, as illustrated:

enter image description here

亢潮 2024-11-17 18:39:41

简而言之,它需要两个列表,遍历第二个列表,然后对于每个项目,从第一个列表中删除同一项目的第一个实例。

> [1..10] \\ [2, 3, 5, 8]
[1,4,6,7,9,10]
> [1, 2, 1, 2, 1, 2] \\ [2]
[1,1,2,1,2]
> [1, 2, 1, 2, 1, 2] \\ [2, 2]
[1,1,1,2]
> [1, 2, 1, 2, 1, 2] \\ [2, 2, 1]
[1,1,2]

Simply put, it takes two lists, goes through the second and for each item, removes the first instance of the same item from the first list.

> [1..10] \\ [2, 3, 5, 8]
[1,4,6,7,9,10]
> [1, 2, 1, 2, 1, 2] \\ [2]
[1,1,2,1,2]
> [1, 2, 1, 2, 1, 2] \\ [2, 2]
[1,1,1,2]
> [1, 2, 1, 2, 1, 2] \\ [2, 2, 1]
[1,1,2]
倾城月光淡如水﹏ 2024-11-17 18:39:41

xs \\ ysxs 中不在 ys 中的所有元素。也许列表理解会澄清这一点:

xs \\ ys = [ x | x <- xs, x `notElem` ys ]

或者,如果你可以在 Haskell 中做到这一点,

xs \\ ys = [ x | x `elem` xs, x `notElem` ys ]

这来自 集合论 的设置差异。基本思想是,您正在从一个元素集合中“减去”另一个元素集合,因此出现了术语“差异”。

xs \\ ys is all the elements in xs that are not in ys. Maybe a list comprehension will clarify this:

xs \\ ys = [ x | x <- xs, x `notElem` ys ]

or, if you could do this in Haskell,

xs \\ ys = [ x | x `elem` xs, x `notElem` ys ]

This comes from set theory's set difference. The basic idea is that you are "subtracting" one collection of elements from another, hence the term "difference".

郁金香雨 2024-11-17 18:39:41

假设您有一个事物列表,例如城市。让我们以这个列表为例:

a = ["London","Brussels","Tokio","Los Angeles","Berlin","Beijing"]

现在您想要删除欧洲的所有城市。您知道,这些城市位于欧洲:

b = ["Glasgow","Paris","Bern","London","Madrid","Amsterdam","Berlin","Brussels"]

要获取 a 中不在欧洲的城市列表,以便不在 b 中,您可以使用 <代码>(\\):

a \\ b = ["Tokio","Los Angeles","Beijing"]

Suppose, you have a list of things, for example cities. Let's take for instance this list:

a = ["London","Brussels","Tokio","Los Angeles","Berlin","Beijing"]

Now you want to remove all cities that are in Europe. You know, that those cities are in Europe:

b = ["Glasgow","Paris","Bern","London","Madrid","Amsterdam","Berlin","Brussels"]

To get a list of cities in a, that are not in Europe, so that are not in b, you can use (\\):

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