简体   繁体   English

似乎无法理解“列表差异”(\\)运算符

[英]Can't seem to get my head around the 'list difference' (\\) operator

I have heard the term 'list difference' (\\) operator in Haskell but still don't quite know how to get my head around it.我在 Haskell 中听说过术语“列表差异” (\\)运算符,但仍然不太清楚如何理解它。 Any examples or ideas?有什么例子或想法吗?

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: (\\)运算符(以及difference function )实现了set difference ,因此,如果您有两个列表ab ,它只返回a中不在b中的那些元素,如图所示:

在此处输入图像描述

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]

xs \\ ys is all the elements in xs that are not in ys . xs \\ ysxs中所有不在ys中的元素。 Maybe a list comprehension will clarify this:也许列表理解会澄清这一点:

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

or, if you could do this in Haskell,或者,如果您可以在 Haskell 中执行此操作,

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

This comes from set theory 'sset difference .这来自于集合论集合差 The basic idea is that you are "subtracting" one collection of elements from another, hence the term "difference".基本思想是您正在从另一个元素集合中“减去”一个元素集合,因此称为“差异”。

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中,您可以使用(\\)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM